"""In-process job runner + SSE event bus.

Hunts and rechecks are blocking (threads + network), so each runs in a daemon thread and
publishes progress events. SSE subscribers get a replay of recent history then live events.
This is the single-node implementation; the same seams swap to arq + Redis for a multi-worker
deploy without touching the routers.
"""
import asyncio
import json
import threading
import traceback
from typing import Callable, Dict, List, Optional


class Job:
    def __init__(self, run_id: str):
        self.run_id = run_id
        self.stop_event = threading.Event()
        self.subscribers: "set[asyncio.Queue]" = set()
        self.history: List[dict] = []
        self.done = False


_jobs: Dict[str, Job] = {}
_loop: Optional[asyncio.AbstractEventLoop] = None

# GitHub's search rate limit is per-token, so it's global across all runs, not per-run.
import time as _time  # noqa: E402

github_rate: Dict = {"remaining": None, "limit": None, "reset": None, "waiting": None, "at": None}


def set_rate(evt: dict) -> None:
    for k in ("remaining", "limit", "reset"):
        if evt.get(k) is not None:
            github_rate[k] = evt[k]
    github_rate["waiting"] = evt.get("waiting")   # None unless currently rate-limited
    github_rate["at"] = _time.time()


def set_loop(loop: asyncio.AbstractEventLoop) -> None:
    global _loop
    _loop = loop


def get_job(run_id: str) -> Optional[Job]:
    return _jobs.get(run_id)


def request_stop(run_id: str) -> bool:
    job = _jobs.get(run_id)
    if not job or job.done:
        return False
    job.stop_event.set()
    return True


def _publish(run_id: str, event: dict) -> None:
    job = _jobs.get(run_id)
    if not job:
        return
    job.history.append(event)
    if len(job.history) > 500:
        job.history = job.history[-500:]
    if _loop is not None:
        for q in list(job.subscribers):
            try:
                _loop.call_soon_threadsafe(q.put_nowait, event)
            except RuntimeError:
                pass


def start_job(run_id: str, target: Callable[[Job, Callable[[dict], None]], None]) -> Job:
    """Run target(job, emit) in a daemon thread; emit publishes to history + subscribers."""
    job = Job(run_id)
    _jobs[run_id] = job

    def emit(event: dict) -> None:
        _publish(run_id, event)

    def runner() -> None:
        try:
            target(job, emit)
        except BaseException as e:  # noqa: BLE001
            emit({"type": "error", "message": f"{type(e).__name__}: {e}"})
            traceback.print_exc()
        finally:
            job.done = True
            emit({"type": "done"})

    threading.Thread(target=runner, name=f"job-{run_id}", daemon=True).start()
    return job


async def event_stream(run_id: str):
    """Async generator of SSE dicts for one run: replay history, then stream live."""
    job = _jobs.get(run_id)
    if not job:
        yield {"data": json.dumps({"type": "error", "message": "unknown run"})}
        yield {"data": json.dumps({"type": "done"})}
        return

    q: "asyncio.Queue" = asyncio.Queue()
    job.subscribers.add(q)
    try:
        for e in list(job.history):        # catch a late viewer up
            yield {"data": json.dumps(e)}
        if job.done:
            return
        while True:
            try:
                e = await asyncio.wait_for(q.get(), timeout=15)
            except asyncio.TimeoutError:
                yield {"event": "ping", "data": "{}"}   # keep the connection warm
                continue
            yield {"data": json.dumps(e)}
            if e.get("type") == "done":
                break
    finally:
        job.subscribers.discard(q)
