"""Non-authoritative local index for faster status reporting."""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List


@dataclass
class LocalIndex:
    path: Path

    def load(self) -> Dict[str, Any]:
        """Load the non-authoritative local index (or return empty)."""
        if not self.path.exists():
            return {"documents": {}, "manifests": {}, "chunks": {}}
        return json.loads(self.path.read_text(encoding="utf-8"))

    def save(self, data: Dict[str, Any]) -> None:
        """Persist the local index to disk."""
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")

    def record_manifest(
        self,
        doc_id: str,
        manifest_hash: str,
        format: str,
        chunking: Dict[str, Any],
        chunks: List[Dict[str, Any]],
    ) -> None:
        """Record a manifest and related metadata into the local index."""
        data = self.load()
        documents = data.setdefault("documents", {})
        manifests = data.setdefault("manifests", {})
        chunks_map = data.setdefault("chunks", {})

        doc_entry = documents.setdefault(doc_id, {"manifests": []})
        if manifest_hash not in doc_entry["manifests"]:
            doc_entry["manifests"].append(manifest_hash)

        manifests[manifest_hash] = {
            "doc_id": doc_id,
            "format": format,
            "chunking": chunking,
            "chunk_count": len(chunks),
            "chunks": chunks,
        }

        for ch in chunks:
            chunk_hash = ch.get("hash")
            if chunk_hash:
                chunks_map.setdefault(chunk_hash, {"seen": True})

        self.save(data)
