"""Local learning preference cache for Avatar plan-v2 enrichment (staging MVP)."""

from __future__ import annotations

import json
from pathlib import Path

from iuve_connect_agents.shared.feature_flags import avatar_learning_enrichment_enabled

DEFAULT_CACHE_PATH = Path.home() / ".local/share/iuve-connect" / "avatar_learning_cache.json"
MAX_CONTEXT_CHARS = 1200


def learning_cache_path() -> Path:
    return DEFAULT_CACHE_PATH


def read_local_preference_context() -> str:
    """Return preference context text when enrichment flag is on and cache exists."""
    if not avatar_learning_enrichment_enabled():
        return ""
    path = learning_cache_path()
    if not path.exists():
        return ""
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return ""
    if not isinstance(payload, dict):
        return ""
    for key in ("preference_context", "context", "summary"):
        value = str(payload.get(key) or "").strip()
        if value:
            return value[:MAX_CONTEXT_CHARS]
    lines = payload.get("preferences")
    if isinstance(lines, list):
        cleaned = [str(item).strip() for item in lines if str(item).strip()]
        if cleaned:
            return "; ".join(cleaned[:8])[:MAX_CONTEXT_CHARS]
    return ""
