"""Thin key store so the engine doesn't care whether results live in Mongo or elsewhere.

One document per key (keyed by the key string itself, so re-finding a key is an idempotent
upsert): status and last_seen refresh, sources/variables union across runs, first_seen is
fixed on first insert, and a checks counter increments each time the key is verified.
"""
from __future__ import annotations

import os
import re
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional

from pymongo import MongoClient, UpdateOne


# Fixed app constants — the same for every deployment, so they live in code, not .env.
# Only the cluster URI (which carries credentials) is environment-specific.
DB_NAME = "ai_key_hunt"
COLLECTION_NAME = "keys"

# Known provider ids and the three result categories, enforced by the DB (below).
PROVIDERS = ["groq", "gemini", "openrouter", "openai", "anthropic",
             "mistral", "xai", "perplexity", "deepseek"]
CATEGORIES = ["working", "valid", "not_working"]

# Server-side JSON Schema: MongoDB rejects writes that don't match. Required fields are the
# ones every upsert always sets; `usage` stays a free-form object (it differs per provider);
# unlisted fields are allowed so the schema can grow without a migration.
KEY_SCHEMA: Dict[str, Any] = {
    "$jsonSchema": {
        "bsonType": "object",
        "required": ["key", "category", "first_seen", "last_seen", "checks"],
        "properties": {
            "key": {"bsonType": "string", "description": "the API key (also the _id)"},
            "provider": {"bsonType": "string"},
            "provider_id": {"enum": PROVIDERS, "description": "normalized provider id"},
            "masked": {"bsonType": "string"},
            "status": {"bsonType": "string", "description": "fine-grained verifier status"},
            "category": {"enum": CATEGORIES, "description": "working | valid | not_working"},
            "verdict": {"bsonType": "string"},
            "detail": {"bsonType": "string"},
            "usage": {"bsonType": "object", "description": "provider-specific, free-form"},
            "sources": {"bsonType": "array", "items": {"bsonType": "string"}},
            "variables": {"bsonType": "array", "items": {"bsonType": "string"}},
            "first_seen": {"bsonType": "date"},
            "last_seen": {"bsonType": "date"},
            "last_run": {"bsonType": "string"},
            "note": {"bsonType": "string", "description": "free-text annotation, user-set"},
            "updated_at": {"bsonType": "date"},
            "checks": {"bsonType": "int", "minimum": 1},
        },
    }
}


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


class KeyStore:
    """Backend-agnostic interface the engine writes through."""

    def upsert_many(self, records: List[Dict], run: Optional[str] = None) -> int:
        raise NotImplementedError

    def query(self, category: Optional[str] = None, provider: Optional[str] = None) -> List[Dict]:
        raise NotImplementedError

    def counts(self) -> Dict[str, int]:
        raise NotImplementedError

    def close(self) -> None:
        pass


class MongoKeyStore(KeyStore):
    def __init__(self, uri: Optional[str] = None, db: str = DB_NAME,
                 collection: str = COLLECTION_NAME, *, _collection=None):
        # `_collection` lets tests inject a mongomock collection instead of connecting.
        if _collection is not None:
            self.coll = _collection
            self._client = None
        else:
            # tz_aware so datetimes come back as UTC-aware (isoformat then carries +00:00, and the
            # browser doesn't misread naive UTC as local time).
            self._client = MongoClient(uri, serverSelectionTimeoutMS=8000,
                                       appname="gh_key_hunter", tz_aware=True)
            db_obj = self._client[db]
            self._apply_schema(db_obj, collection)
            self.coll = db_obj[collection]
        self._ensure_indexes()

    @staticmethod
    def _apply_schema(db_obj, collection: str) -> None:
        """Create the collection with the JSON-Schema validator, or apply it to an existing one.

        Skipped silently if the cluster won't allow it (e.g. restricted role) — the data model
        still works, it just isn't server-enforced.
        """
        try:
            if collection in db_obj.list_collection_names():
                db_obj.command("collMod", collection, validator=KEY_SCHEMA,
                               validationLevel="moderate", validationAction="error")
            else:
                db_obj.create_collection(collection, validator=KEY_SCHEMA,
                                         validationLevel="moderate", validationAction="error")
        except Exception as e:  # noqa: BLE001 — never let schema setup break a run
            print(f"[DB] schema not applied ({type(e).__name__}: {e}); continuing without it")

    def _ensure_indexes(self) -> None:
        for field in ("category", "provider_id", "status", "last_seen"):
            self.coll.create_index(field)
        # Prefix/substring search on the key falls back to a scan without this; keep it cheap.
        self.coll.create_index("key")

    def upsert_many(self, records: List[Dict], run: Optional[str] = None) -> int:
        now = _now()
        ops = []
        for r in records:
            key = r.get("key")
            if not key:
                continue
            set_fields = {k: v for k, v in {
                "key": key,
                "provider": r.get("provider"),
                "provider_id": r.get("provider_id") or r.get("provider_hint"),
                "masked": r.get("masked"),
                "status": r.get("status"),
                "category": r.get("category"),
                "verdict": r.get("verdict"),
                "detail": r.get("detail"),
                "usage": r.get("usage"),
                "last_seen": now,
                "last_run": run,
            }.items() if v is not None}

            update: Dict[str, Any] = {
                "$set": set_fields,
                "$setOnInsert": {"first_seen": now},
                "$inc": {"checks": 1},
            }
            add = {}
            if r.get("sources"):
                add["sources"] = {"$each": list(r["sources"])}
            if r.get("variables"):
                add["variables"] = {"$each": list(r["variables"])}
            if add:
                update["$addToSet"] = add

            ops.append(UpdateOne({"_id": key}, update, upsert=True))

        if not ops:
            return 0
        res = self.coll.bulk_write(ops, ordered=False)
        return (res.upserted_count or 0) + (res.modified_count or 0)

    def query(self, category: Optional[str] = None, provider: Optional[str] = None) -> List[Dict]:
        q: Dict[str, Any] = {}
        if category:
            q["category"] = category
        if provider:
            q["provider_id"] = provider
        out = []
        for d in self.coll.find(q):
            d.pop("_id", None)
            for f in ("first_seen", "last_seen"):
                if isinstance(d.get(f), datetime):
                    d[f] = d[f].isoformat()
            out.append(d)
        return out

    def counts(self) -> Dict[str, int]:
        res: Dict[str, int] = {}
        for row in self.coll.aggregate([{"$group": {"_id": "$category", "n": {"$sum": 1}}}]):
            res[row["_id"] or "unknown"] = row["n"]
        return res

    @staticmethod
    def _build_filter(filters: Dict[str, Any]) -> Dict[str, Any]:
        """Translate API filters into a Mongo query. Only non-empty filters are applied."""
        q: Dict[str, Any] = {}
        for field in ("category", "provider_id"):
            if filters.get(field):
                q[field] = filters[field]
        if filters.get("run"):
            q["last_run"] = filters["run"]     # keys whose most recent run was this one
        if filters.get("noted"):
            q["note"] = {"$exists": True, "$nin": [None, ""]}   # only keys you've annotated
        status = filters.get("status")
        if status == "unconfirmed":
            q["status"] = None          # matches a missing or null status (never generate-tested)
        elif status:
            q["status"] = status
        if filters.get("variable"):
            q["variables"] = filters["variable"]
        if filters.get("repo"):
            # sources look like "owner/repo/path"; match the repo prefix.
            q["sources"] = {"$regex": "^" + re.escape(filters["repo"])}
        if filters.get("q"):
            frag = re.escape(filters["q"])
            q["$or"] = [{"key": {"$regex": frag}}, {"masked": {"$regex": frag}},
                        {"note": {"$regex": frag, "$options": "i"}}]
        if filters.get("since"):
            q["last_seen"] = {"$gte": filters["since"]}
        return q

    # Keys always surface best-first: working, then valid, then not_working.
    _CAT_RANK = {"$switch": {"branches": [
        {"case": {"$eq": ["$category", "working"]}, "then": 0},
        {"case": {"$eq": ["$category", "valid"]}, "then": 1},
        {"case": {"$eq": ["$category", "not_working"]}, "then": 2},
    ], "default": 3}}

    def query_page(self, filters: Optional[Dict[str, Any]] = None, *, sort: str = "last_seen",
                   order: int = -1, page: int = 1, limit: int = 50):
        """Return (rows, total) for one page of keys matching `filters`, ranked working →
        valid → not_working, then by `sort` within each bucket."""
        q = self._build_filter(filters or {})
        total = self.coll.count_documents(q)
        page = max(1, page)
        limit = max(1, min(limit, 500))
        pipeline = [
            {"$match": q},
            {"$addFields": {"_catrank": self._CAT_RANK}},
            {"$sort": {"_catrank": 1, sort: order, "_id": 1}},
            {"$skip": (page - 1) * limit},
            {"$limit": limit},
            {"$project": {"_catrank": 0}},
        ]
        rows = []
        for d in self.coll.aggregate(pipeline):
            d.pop("_id", None)
            for f in ("first_seen", "last_seen"):
                if isinstance(d.get(f), datetime):
                    d[f] = d[f].isoformat()
            rows.append(d)
        return rows, total

    def update_usage_many(self, usage_by_key: Dict[str, Dict]) -> int:
        """Attach capability/usage (`usage` blob, incl. `models`) to existing keys WITHOUT touching
        their status or category — a quick, non-destructive enrichment."""
        now = _now()
        ops = [UpdateOne({"_id": k}, {"$set": {"usage": u, "updated_at": now}})
               for k, u in usage_by_key.items() if u]
        if not ops:
            return 0
        res = self.coll.bulk_write(ops, ordered=False)
        return res.modified_count or 0

    def set_note(self, key: str, note: str) -> bool:
        """Attach (or clear) a free-text note on one key. Survives rechecks — upsert_many
        never touches `note`."""
        res = self.coll.update_one(
            {"_id": key}, {"$set": {"note": note, "updated_at": _now()}})
        return res.matched_count > 0

    def get_by_key(self, key: str) -> Optional[Dict]:
        d = self.coll.find_one({"_id": key})
        if not d:
            return None
        d.pop("_id", None)
        for f in ("first_seen", "last_seen"):
            if isinstance(d.get(f), datetime):
                d[f] = d[f].isoformat()
        return d

    def stats(self, filters: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """Counts by category and by provider. With `filters` (same keys as query), scope to that
        subset — e.g. `{"run": rid}` for one run's breakdown."""
        match = self._build_filter(filters or {})
        pre = [{"$match": match}] if match else []

        def group(field: str) -> Dict[str, int]:
            out: Dict[str, int] = {}
            for row in self.coll.aggregate(pre + [{"$group": {"_id": f"${field}", "n": {"$sum": 1}}}]):
                out[row["_id"] or "unknown"] = row["n"]
            return out

        by_category = group("category")
        return {"total": sum(by_category.values()),
                "by_category": by_category, "by_provider": group("provider_id")}

    def close(self) -> None:
        if self._client is not None:
            self._client.close()


def store_from_env() -> Optional[MongoKeyStore]:
    """Build a store from MONGODB_URI (.env), or None if no URI is set (file-only mode).

    The database and collection names are fixed app constants (DB_NAME / COLLECTION_NAME),
    so only the credential-bearing URI comes from the environment.
    """
    uri = os.getenv("MONGODB_URI")
    if not uri:
        return None
    return MongoKeyStore(uri=uri)
