"""Single-process bounded queue. Only status/results survive in SQLite after inference."""
import fcntl
import json
import os
import sqlite3
import threading
import time
import uuid
from pathlib import Path

from engine import BadAudio, Cancelled


class Busy(Exception):
    pass


class Store:
    def __init__(self, data: Path, engine, max_jobs: int, max_seconds: int, ttl: int):
        self.data, self.engine, self.max_jobs, self.max_seconds, self.ttl = data, engine, max_jobs, max_seconds, ttl
        self.cv = threading.Condition()
        self.cancel = threading.Event()
        self.active = None
        self.reserved = 0
        self.stopping = False

    def start(self):
        self.data.mkdir(parents=True, exist_ok=True, mode=0o700)
        self.uploads = self.data / "uploads"
        self.uploads.mkdir(exist_ok=True, mode=0o700)
        self.lock = (self.data / "service.lock").open("a", encoding="utf8")
        fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        self.db = sqlite3.connect(self.data / "jobs.sqlite", check_same_thread=False, isolation_level=None)
        self.db.row_factory = sqlite3.Row
        self.db.execute("CREATE TABLE IF NOT EXISTS jobs (id TEXT PRIMARY KEY,state TEXT,updated REAL,results TEXT,needs_cancel INTEGER DEFAULT 0)")
        self.db.execute("UPDATE jobs SET state='failed',updated=?,results=? WHERE state IN ('processing','queued')",
                        (time.time(), json.dumps({"error": "Сервер дахин ассан тул бичлэгээ шинээр оруулна уу."})))
        for path in self.uploads.glob("*.audio"):
            path.unlink(missing_ok=True)
        self.thread = threading.Thread(target=self._run, daemon=True, name="mn-recognizer")
        self.thread.start()

    def stop(self):
        with self.cv:
            self.stopping = True
            self.cancel.set()
            self.cv.notify_all()
        self.thread.join()
        self.db.close()
        self.lock.close()

    def reserve(self):
        with self.cv:
            self.clear_expired()
            total = self.db.execute("SELECT count(*) FROM jobs WHERE state IN ('queued','processing')").fetchone()[0]
            if total + self.reserved >= self.max_jobs:
                raise Busy()
            self.reserved += 1
            return uuid.uuid4().hex

    def release(self):
        with self.cv:
            self.reserved -= 1

    def path(self, job_id):
        return self.uploads / (job_id + ".audio")

    def submit(self, job_id):
        with self.cv:
            self.db.execute("INSERT INTO jobs(id,state,updated) VALUES(?,'queued',?)", (job_id, time.time()))
            self.cv.notify()

    def clear_expired(self):
        self.db.execute("DELETE FROM jobs WHERE state NOT IN ('queued','processing') AND updated < ?",
                        (time.time() - self.ttl,))

    def status(self, job_id):
        with self.cv:
            self.clear_expired()
            row = self.db.execute("SELECT * FROM jobs WHERE id=?", (job_id,)).fetchone()
            if row is None:
                return None
            return {"id": row["id"], "status": row["state"], "cancelRequested": bool(row["needs_cancel"]),
                    **(json.loads(row["results"]) if row["results"] else {})}

    def cancel_job(self, job_id):
        with self.cv:
            row = self.db.execute("SELECT state FROM jobs WHERE id=?", (job_id,)).fetchone()
            if row and row[0] == "queued":
                self.path(job_id).unlink(missing_ok=True)
                self.db.execute("UPDATE jobs SET state='cancelled',updated=?,needs_cancel=1 WHERE id=?", (time.time(), job_id))
            elif row and row[0] == "processing" and self.active == job_id:
                self.db.execute("UPDATE jobs SET needs_cancel=1 WHERE id=?", (job_id,))
                self.cancel.set()
            return self.status(job_id)

    def _run(self):
        while True:
            with self.cv:
                self.clear_expired()
                if self.stopping:
                    return
                row = self.db.execute("SELECT id FROM jobs WHERE state='queued' ORDER BY updated LIMIT 1").fetchone()
                if row is None:
                    self.cv.wait(timeout=min(60, self.ttl))
                    continue
                job_id = row[0]
                self.active, self.cancel = job_id, threading.Event()
                self.db.execute("UPDATE jobs SET state='processing',updated=? WHERE id=?", (time.time(), job_id))
            try:
                data = self.engine.recognize(self.path(job_id), self.cancel, self.max_seconds)
                state = "done"
            except Cancelled:
                state, data = "cancelled", {}
            except BadAudio as error:
                state, data = "failed", {"error": str(error)}
            except Exception:
                state, data = "failed", {"error": "Танилт амжилтгүй боллоо. Загвар ба серверийн санах ойг шалгана уу."}
            finally:
                self.path(job_id).unlink(missing_ok=True)
            with self.cv:
                if self.cancel.is_set():
                    state, data = "cancelled", {}
                self.db.execute("UPDATE jobs SET state=?,updated=?,results=? WHERE id=?",
                                (state, time.time(), json.dumps(data, ensure_ascii=False), job_id))
                self.active = None
