"""progress.py - sledovani prubehu chat jobu (in-memory)."""
import threading
import time
from dataclasses import dataclass
from typing import Any


@dataclass
class Job:
    job_id: str
    started: float
    phase: str = "init"
    percent: int = 0
    detail: str = "Zahajuji..."
    done: bool = False
    result: dict[str, Any] | None = None
    error: str | None = None
    tool_count: int = 0

_lock = threading.Lock()
_jobs: dict[str, Job] = {}

def create(job_id: str) -> Job:
    with _lock:
        j = Job(job_id=job_id, started=time.time())
        _jobs[job_id] = j
        return j

def set_phase(job_id: str, phase: str, percent: int, detail: str) -> None:
    with _lock:
        j = _jobs.get(job_id)
        if j:
            j.phase = phase; j.percent = percent; j.detail = detail

def add_tool(job_id: str, tool_name: str) -> None:
    with _lock:
        j = _jobs.get(job_id)
        if j:
            j.tool_count += 1
            j.percent = min(30 + j.tool_count * 15, 85)
            j.phase = "tool"
            j.detail = "Volam tool: " + tool_name

def finish(job_id: str, result=None, error=None) -> None:
    with _lock:
        j = _jobs.get(job_id)
        if j:
            j.done = True; j.percent = 100; j.phase = "done"
            j.detail = "Dokonceno"; j.result = result; j.error = error

def snapshot(job_id: str) -> dict[str, Any] | None:
    with _lock:
        j = _jobs.get(job_id)
        if not j:
            return None
        return {
            "job_id": j.job_id, "phase": j.phase, "percent": j.percent,
            "detail": j.detail, "elapsed": round(time.time() - j.started, 1),
            "done": j.done, "error": j.error, "tool_count": j.tool_count,
            "result": j.result if j.done else None,
        }

def cleanup_old(max_age_sec: int = 3600) -> None:
    cutoff = time.time() - max_age_sec
    with _lock:
        for jid in list(_jobs.keys()):
            if _jobs[jid].started < cutoff:
                del _jobs[jid]
