from __future__ import annotations

import json
from pathlib import Path
from typing import Any


def learned_path(home: Path, project: str, function: str) -> Path:
    return home / "external" / project / "_learned" / f"{function}.md"


def _summarize_payload(payload: Any) -> str:
    if isinstance(payload, dict):
        if not payload:
            return "(empty)"
        parts = [f"{key}={value}" for key, value in payload.items()]
        return ", ".join(parts)
    if isinstance(payload, list):
        return f"[{len(payload)} items]"
    return str(payload)


def _summarize_record(envelope: dict[str, Any]) -> str:
    record_id = str(envelope.get("record_id") or "")
    occurred_at = str(envelope.get("occurred_at") or "")
    payload = envelope.get("payload", {})
    summary = _summarize_payload(payload)
    return f"- **{record_id}** ({occurred_at}): {summary}"


def _load_records(home: Path, project: str, function: str) -> list[dict[str, Any]]:
    base = home / "external" / project / function
    if not base.is_dir():
        return []
    records: list[dict[str, Any]] = []
    for path in sorted(base.glob("*.json")):
        if path.name.startswith("_"):
            continue
        try:
            records.append(json.loads(path.read_text(encoding="utf-8")))
        except (json.JSONDecodeError, OSError):
            continue
    return records


def distill_function(home: Path, project: str, function: str) -> str:
    """规则拼接 function 下全部 record 摘要，写入 _learned/{function}.md。"""
    records = _load_records(home, project, function)
    lines = [
        f"# {function}",
        "",
        f"Records: {len(records)}",
        "",
    ]
    for record in records:
        lines.append(_summarize_record(record))
    content = "\n".join(lines).rstrip() + "\n"
    path = learned_path(home, project, function)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")
    return str(path)


def maybe_learn_after_write(
    home: Path,
    project: str,
    function: str,
    envelope: dict[str, Any],
    mode: str,
) -> bool:
    """mode=off/manual 不学习；mode=auto 在写入成功后增量更新摘要。"""
    del envelope  # reserved for future incremental hints
    if str(mode or "off").strip().lower() != "auto":
        return False
    distill_function(home, project, function)
    return True
