from __future__ import annotations

import json
from dataclasses import dataclass


@dataclass
class SimpleIndexer:
    """
    A pragmatic, lightweight "indexer" that builds a JSON inverted index over symbols.
    This is NOT a vector DB; it's cheap and explainable, and good enough for lightweight retrieval.
    """

    def build_inverted_index(self, *, symbols: dict, files: dict) -> dict:
        inv: dict[str, list[str]] = {}

        def add_token(tok: str, sid: str) -> None:
            tok = tok.strip().lower()
            if not tok:
                return
            inv.setdefault(tok, []).append(sid)

        for sid, sym in symbols.items():
            add_token(sym.get("name", ""), sid)
            add_token(sym.get("qualname", ""), sid)
            for deco in sym.get("decorators", []) or []:
                add_token(deco, sid)

        # basic file-level tokens
        for path, meta in files.items():
            facts = meta.get("facts") or {}
            for imp in facts.get("imports", []) or []:
                mod = (imp.get("module") or "").strip()
                if mod:
                    inv.setdefault(mod.lower(), [])

        # dedupe lists while preserving insertion order
        for k, v in list(inv.items()):
            seen: set[str] = set()
            deduped: list[str] = []
            for sid in v:
                if sid in seen:
                    continue
                seen.add(sid)
                deduped.append(sid)
            inv[k] = deduped
        return inv

    def save(self, index: dict, out_path: str) -> None:
        with open(out_path, "w", encoding="utf-8") as f:
            json.dump(index, f, ensure_ascii=False, indent=2)

