"""The `queries` collection: the editable query set + each query's productivity history.

One document per query string (the query IS its identity). Seeded from the hunter's
DEFAULT_QUERIES on first use. After every run, each query's phase-1 yield (authenticated vs
rejected) is recorded, so the UI can show which queries earn their rate-limit slot.
"""
from datetime import datetime, timezone
from typing import Dict, List, Optional

import gh_key_hunter

from .db import get_store


# Default per-query file cap = 10 pages (the API's own 1000-result page limit). Raise it on the
# producers to let them partition deeper; 0 means unlimited (full size-partition).
DEFAULT_CAP = 1000


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


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


class QueryStore:
    def __init__(self, coll=None):
        self.coll = coll or get_store().coll.database["queries"]
        self.seed()

    def seed(self) -> None:
        if self.coll.count_documents({}) == 0:
            now = _now()
            self.coll.insert_many([{
                "_id": q, "query": q, "enabled": True, "tier": "default", "note": "",
                "cap": DEFAULT_CAP,
                "created_at": now, "updated_at": now, "last_run": None, "last_seen": None,
                "stats": {"runs": 0, "authok": 0, "rejected": 0, "last_authok": 0, "last_rejected": 0},
                "history": [],
            } for q in gh_key_hunter.DEFAULT_QUERIES])

    def list(self) -> List[Dict]:
        out = []
        for d in self.coll.find().sort([("enabled", -1), ("_id", 1)]):
            d["query"] = d.pop("_id")
            d.setdefault("cap", DEFAULT_CAP)   # backfill for docs created before caps existed
            out.append(_iso(d))
        return out

    def enabled_with_caps(self):
        """(ordered query strings, {query: cap}) for a run. cap<=0 is omitted (unlimited)."""
        queries, caps = [], {}
        for d in self.coll.find({"enabled": True}):
            q = d["_id"]
            queries.append(q)
            cap = d.get("cap", DEFAULT_CAP)
            if cap and cap > 0:
                caps[q] = cap
        return queries, caps

    def add(self, query: str, tier: str = "custom", note: str = "", cap: int = DEFAULT_CAP) -> None:
        now = _now()
        self.coll.update_one({"_id": query}, {
            "$setOnInsert": {
                "query": query, "enabled": True, "tier": tier, "note": note, "cap": cap,
                "created_at": now, "last_run": None, "last_seen": None,
                "stats": {"runs": 0, "authok": 0, "rejected": 0, "last_authok": 0, "last_rejected": 0},
                "history": [],
            },
            "$set": {"updated_at": now},
        }, upsert=True)

    def update(self, query: str, enabled: Optional[bool] = None,
               note: Optional[str] = None, tier: Optional[str] = None,
               new_query: Optional[str] = None, cap: Optional[int] = None) -> None:
        fields: Dict = {"updated_at": _now()}
        if enabled is not None:
            fields["enabled"] = enabled
        if note is not None:
            fields["note"] = note
        if tier is not None:
            fields["tier"] = tier
        if cap is not None:
            fields["cap"] = cap

        if new_query and new_query != query:
            # The query string is the _id, so renaming = copy the doc then drop the old one.
            doc = self.coll.find_one({"_id": query})
            if doc:
                doc.update({"_id": new_query, "query": new_query})
                doc.update({k: v for k, v in fields.items()})
                self.coll.delete_one({"_id": query})
                self.coll.replace_one({"_id": new_query}, doc, upsert=True)
            return
        self.coll.update_one({"_id": query}, {"$set": fields})

    def delete(self, query: str) -> None:
        self.coll.delete_one({"_id": query})

    def record_run(self, per_query: Dict[str, Dict], run_id: str) -> None:
        now = _now()
        for q, pq in per_query.items():
            authok = len(pq.get("working", []))     # phase-1 authenticated (valid candidates)
            rejected = len(pq.get("not_working", []))  # phase-1 rejected (dead/leaked)
            self.coll.update_one({"_id": q}, {
                "$set": {"last_run": run_id, "last_seen": now,
                         "stats.last_authok": authok, "stats.last_rejected": rejected},
                "$inc": {"stats.runs": 1, "stats.authok": authok, "stats.rejected": rejected},
                "$push": {"history": {
                    "$each": [{"run": run_id, "authok": authok, "rejected": rejected}],
                    "$slice": -12}},
            }, upsert=True)
