"""The `runs` collection: one document per hunt or recheck, with live status + counts.

The complete, timestamped log of every run lives in a sibling `run_logs` collection (one
document per run) so a finished run can be reopened and read end to end — the run doc keeps
only a short `log_tail` for the at-a-glance view.
"""
import re
import uuid
from datetime import datetime, timezone
from typing import Dict, List, Optional

from .db import get_store


def _now() -> datetime:
    return datetime.now(timezone.utc)


_TAG = re.compile(r"^\[([a-z]+)\]")


def _level(message: str) -> str:
    """Classify a log line by its leading [tag] so the console can color it."""
    m = _TAG.match(message or "")
    return m.group(1) if m else "info"


def _iso(d: Dict) -> Dict:
    for f in ("started_at", "finished_at"):
        if isinstance(d.get(f), datetime):
            d[f] = d[f].isoformat()
    return d


class RunStore:
    def __init__(self, coll=None):
        # `runs` lives in the same database as `keys`.
        self.coll = coll or get_store().coll.database["runs"]

    def create(self, kind: str, queries: List[str], depth: str) -> str:
        rid = _now().strftime("%Y%m%d_%H%M%S_") + uuid.uuid4().hex[:6]
        self.coll.insert_one({
            "_id": rid, "kind": kind, "queries": queries, "depth": depth,
            "status": "running", "phase": "search",
            "started_at": _now(), "finished_at": None,
            "counts": {"working": 0, "valid": 0, "not_working": 0,
                       "candidates": 0, "dead": 0, "files": 0, "fetched": 0},
            "progress": {"done": 0, "total": 0},
            "rate": {"remaining": None, "limit": None, "reset": None},
            "heartbeat": _now(),   # bumped as the run works; stale → startup may mark it interrupted
            "log_tail": [],
        })
        return rid

    def set(self, rid: str, **fields) -> None:
        self.coll.update_one({"_id": rid}, {"$set": fields})

    def push_log(self, rid: str, line: str) -> None:
        self.coll.update_one({"_id": rid},
                             {"$push": {"log_tail": {"$each": [line], "$slice": -60}}})

    def finish(self, rid: str, status: str, counts: Optional[Dict] = None) -> None:
        upd: Dict = {"status": status, "finished_at": _now()}
        if counts:
            # Merge terminal tallies into the counts subdoc — don't clobber the live
            # fetched/files/candidates/dead that the pipeline view reads.
            for k, v in counts.items():
                upd[f"counts.{k}"] = v
        self.coll.update_one({"_id": rid}, {"$set": upd})

    def get(self, rid: str) -> Optional[Dict]:
        d = self.coll.find_one({"_id": rid})
        if not d:
            return None
        d["id"] = d.pop("_id")
        return _iso(d)

    def list(self, limit: int = 50) -> List[Dict]:
        out = []
        for d in self.coll.find().sort("started_at", -1).limit(limit):
            d["id"] = d.pop("_id")
            out.append(_iso(d))
        return out


class LogStore:
    """The full, append-only log of each run: `run_logs` doc `{_id, count, lines:[{t,m,l}]}`."""

    # A hard ceiling so a pathological run can't push one doc past Mongo's 16MB limit; far above
    # any real run (10 req/min caps line volume), so `after`/`next` paging stays absolute.
    MAX_LINES = 50000

    def __init__(self, coll=None):
        self.coll = coll or get_store().coll.database["run_logs"]

    def append(self, rid: str, message: str) -> None:
        self.coll.update_one(
            {"_id": rid},
            {"$push": {"lines": {"$each": [{"t": _now(), "m": message, "l": _level(message)}],
                                 "$slice": -self.MAX_LINES}},
             "$inc": {"count": 1}},
            upsert=True,
        )

    def page(self, rid: str, after: int = 0, limit: int = 2000) -> Dict:
        after = max(0, int(after))
        limit = max(1, min(int(limit), 5000))
        doc = self.coll.find_one({"_id": rid}, {"count": 1, "lines": {"$slice": [after, limit]}})
        if not doc:
            return {"lines": [], "total": 0, "next": after}
        out = []
        for i, ln in enumerate(doc.get("lines") or []):
            t = ln.get("t")
            out.append({"n": after + i,
                        "t": t.isoformat() if isinstance(t, datetime) else t,
                        "m": ln.get("m", ""), "l": ln.get("l", "info")})
        total = int(doc.get("count", after + len(out)))
        return {"lines": out, "total": total, "next": after + len(out)}
