"""
Preferences
Stores team preferences and auto-detects defaults from usage.
"""
import json
from pathlib import Path
from typing import Dict, Any, Optional
from .usage_tracker import UsageTracker

class Preferences:
    def __init__(self, data_dir: Path):
        self.data_dir = data_dir / "learning"
        self.data_dir.mkdir(parents=True, exist_ok=True)
        self.prefs_file = self.data_dir / "preferences.json"
        if not self.prefs_file.exists():
            self.prefs_file.write_text("{}", encoding="utf-8")

    def _read(self) -> Dict[str, Any]:
        try:
            return json.loads(self.prefs_file.read_text(encoding="utf-8"))
        except Exception:
            return {}

    def _write(self, data: Dict[str, Any]):
        self.prefs_file.write_text(json.dumps(data, indent=2), encoding="utf-8")

    def auto_detect(self, tracker: UsageTracker) -> Dict[str, Any]:
        top_models = tracker.top_models(days=30, limit=1)
        top_strats = tracker.top_strategies(days=30, limit=1)
        
        pref_model = top_models[0]["model"] if top_models else "claude"
        pref_strat = top_strats[0]["strategy"] if top_strats else "sequential"
        
        prefs = self._read()
        prefs["preferred_model"] = pref_model
        prefs["preferred_strategy"] = pref_strat
        prefs["default_temperature"] = 0.7
        self._write(prefs)
        
        return {"preferred_model": pref_model, "preferred_strategy": pref_strat, "default_temperature": 0.7}

    def save(self, key: str, value: Any):
        prefs = self._read()
        prefs[key] = value
        self._write(prefs)

    def get(self, key: str, default: Any = None) -> Any:
        return self._read().get(key, default)

    def get_all(self) -> Dict[str, Any]:
        return self._read()

    def apply_to_request(self, request: Dict[str, Any]) -> Dict[str, Any]:
        prefs = self._read()
        if "model" not in request and "preferred_model" in prefs:
            request["model"] = prefs["preferred_model"]
        if "strategy" not in request and "preferred_strategy" in prefs:
            request["strategy"] = prefs["preferred_strategy"]
        if "temperature" not in request and "default_temperature" in prefs:
            request["temperature"] = prefs["default_temperature"]
        return request

    def reset(self, key: Optional[str] = None):
        if key is None:
            self._write({})
        else:
            prefs = self._read()
            if key in prefs:
                del prefs[key]
                self._write(prefs)

    def export_prefs(self, filepath: str):
        Path(filepath).write_text(json.dumps(self._read(), indent=2), encoding="utf-8")

    def import_prefs(self, filepath: str):
        try:
            data = json.loads(Path(filepath).read_text(encoding="utf-8"))
            prefs = self._read()
            prefs.update(data)
            self._write(prefs)
        except Exception:
            pass

    def override(self, overrides: Dict[str, Any]) -> Dict[str, Any]:
        prefs = self._read()
        return {**prefs, **overrides}

    def diff(self, other_filepath: str) -> Dict[str, Any]:
        try:
            other = json.loads(Path(other_filepath).read_text(encoding="utf-8"))
        except Exception:
            other = {}
            
        current = self._read()
        added = {k: v for k, v in other.items() if k not in current}
        removed = {k: v for k, v in current.items() if k not in other}
        changed = {k: {"old": current[k], "new": other[k]} for k in current if k in other and current[k] != other[k]}
        
        return {"added": added, "removed": removed, "changed": changed}
