from __future__ import annotations

import json
from dataclasses import dataclass
from threading import RLock
import unicodedata
from pathlib import Path
from typing import TYPE_CHECKING, Any

from keepedu_performance.core.config import settings
from keepedu_performance.core.paths import RUNTIME_ROOT

if TYPE_CHECKING:
    from keepedu_performance.api.repository import Tenant


@dataclass(frozen=True)
class _PartitionSignature:
    files: tuple[tuple[str, int, int], ...]


_cache_lock = RLock()
_partition_cache: dict[
    tuple[str, str], tuple[_PartitionSignature, list[dict[str, Any]]]
] = {}
_merged_cache: dict[
    tuple[str, str, tuple[str, ...]], tuple[_PartitionSignature, dict[str, Any] | None]
] = {}


def tenant_root(tenant: Tenant) -> Path:
    return (
        RUNTIME_ROOT
        / settings.tenant_data_path
        / tenant.institute_id
        / str(tenant.year)
    )


def read_json(path: Path, default: Any = None) -> Any:
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except FileNotFoundError:
        return default


def _partition_files(root: Path) -> tuple[list[Path], _PartitionSignature]:
    if not root.is_dir():
        return [], _PartitionSignature(())
    paths = sorted(root.rglob("data.json"), key=lambda item: item.stat().st_mtime_ns)
    signature = _PartitionSignature(
        tuple(
            (str(path.relative_to(root)), stat.st_mtime_ns, stat.st_size)
            for path in paths
            for stat in (path.stat(),)
        )
    )
    return paths, signature


def clear_partition_cache() -> None:
    """Clear in-process data caches, mainly for tests and explicit maintenance."""
    with _cache_lock:
        _partition_cache.clear()
        _merged_cache.clear()


def load_partitions(tenant: Tenant, entity: str) -> list[dict[str, Any]]:
    root = tenant_root(tenant) / "gold" / "dashboard" / entity
    paths, signature = _partition_files(root)
    cache_key = (str(root), entity)
    with _cache_lock:
        cached = _partition_cache.get(cache_key)
        if cached and cached[0] == signature:
            return cached[1]
        result: list[dict[str, Any]] = []
        for path in paths:
            payload = read_json(path)
            if isinstance(payload, dict):
                result.append(payload)
        _partition_cache[cache_key] = (signature, result)
        return result


def load_merged_partitions(
    tenant: Tenant, entity: str, fields: tuple[str, ...]
) -> dict[str, Any] | None:
    """Load and merge an entity once until one of its partition files changes."""
    root = tenant_root(tenant) / "gold" / "dashboard" / entity
    _, signature = _partition_files(root)
    cache_key = (str(root), entity, fields)
    with _cache_lock:
        cached = _merged_cache.get(cache_key)
        if cached and cached[0] == signature:
            return cached[1]
        merged = merge_partition_lists(load_partitions(tenant, entity), fields)
        _merged_cache[cache_key] = (signature, merged)
        return merged


def scope_key(unit: object, series: object) -> str:
    def normalize(value: object) -> str:
        text = unicodedata.normalize("NFC", str(value or "")).strip().upper()
        return " ".join(text.split())

    return f"{normalize(unit)}\0{normalize(series)}"


def merge_partition_lists(
    partitions: list[dict[str, Any]], fields: tuple[str, ...]
) -> dict[str, Any] | None:
    if not partitions:
        return None
    merged = {**partitions[-1]}
    values: dict[str, list[dict[str, Any]]] = {field: [] for field in fields}
    for partition in partitions:
        metadata = partition.get("partition") or {}
        rows = partition.get(fields[0]) or []
        if metadata.get("serie"):
            scopes = {scope_key(metadata.get("unidade"), metadata.get("serie"))}
        else:
            scopes = {scope_key(row.get("unidade"), row.get("serie")) for row in rows}
        for field in fields:
            existing = values[field]
            values[field] = [
                row
                for row in existing
                if scope_key(row.get("unidade"), row.get("serie")) not in scopes
            ] + list(partition.get(field) or [])
    merged.update(values)
    return merged


def legacy_gold_file(tenant: Tenant, filename: str) -> Path | None:
    if tenant.institute_id not in settings.keepedu_institute_ids:
        return None
    return RUNTIME_ROOT / settings.gold_path / filename
