"""
Anonymous Telemetry
Handles optional sharing of usage metadata with the network.
"""
import json
import time
import uuid
import hashlib
import platform
import socket
from pathlib import Path
from typing import Dict, Any
from runtime.learning.usage_tracker import UsageTracker

BLOCKED_FIELDS = {"prompt", "response", "content", "user", "email", "token", "key", "path", "file"}

class TelemetryManager:
    def __init__(self, data_dir: Path):
        self.data_dir = data_dir
        self.config_file = self.data_dir / "config.json"
        self.outbox_dir = self.data_dir / "telemetry_outbox"
        self.outbox_dir.mkdir(parents=True, exist_ok=True)
        self.salt_file = self.data_dir / "instance_salt"

    def _load_config(self) -> Dict[str, Any]:
        if not self.config_file.exists():
            return {}
        try:
            return json.loads(self.config_file.read_text("utf-8"))
        except:
            return {}

    def _save_config(self, cfg: Dict[str, Any]):
        self.config_file.write_text(json.dumps(cfg, indent=2), "utf-8")

    def is_opted_in(self) -> bool:
        return self._load_config().get("telemetry_enabled", False)

    def opt_in(self):
        cfg = self._load_config()
        cfg["telemetry_enabled"] = True
        self._save_config(cfg)

    def opt_out(self):
        cfg = self._load_config()
        cfg["telemetry_enabled"] = False
        self._save_config(cfg)
        # Delete pending reports
        for f in self.outbox_dir.glob("*.json"):
            try:
                f.unlink()
            except:
                pass

    def get_instance_id(self) -> str:
        if not self.salt_file.exists():
            self.salt_file.write_text(str(uuid.uuid4()), "utf-8")
        salt = self.salt_file.read_text("utf-8").strip()
        hostname = socket.gethostname()
        return hashlib.sha256(f"{hostname}-{salt}".encode("utf-8")).hexdigest()[:16]

    def prepare_report(self, tracker: UsageTracker, days: int = 7) -> Dict[str, Any]:
        stats = tracker.get_stats(days)
        top_models = tracker.top_models(days, limit=100)
        top_strats = tracker.top_strategies(days, limit=100)
        
        model_usage = {m["model"]: m["count"] for m in top_models}
        avg_latency_by_model = {m["model"]: m["avg_latency_ms"] for m in top_models}
        strategy_usage = {s["strategy"]: s["count"] for s in top_strats}
        
        return {
            "instance_id": self.get_instance_id(),
            "period_days": days,
            "total_interactions": stats["total_interactions"],
            "model_usage": model_usage,
            "strategy_usage": strategy_usage,
            "avg_latency_by_model": avg_latency_by_model,
            "os_platform": platform.system()
        }

    def preview_report(self, tracker: UsageTracker) -> Dict[str, Any]:
        return self.prepare_report(tracker)

    def validate_privacy(self, report: Dict[str, Any]) -> bool:
        """Check for blocked fields recursively."""
        def check(obj):
            if isinstance(obj, dict):
                for k, v in obj.items():
                    if k.lower() in BLOCKED_FIELDS:
                        return False
                    if not check(v):
                        return False
            elif isinstance(obj, list):
                for item in obj:
                    if not check(item):
                        return False
            elif isinstance(obj, str):
                # Optionally check if string itself contains json with blocked fields, but simple key match is usually enough
                pass
            return True
        return check(report)

    def send_report(self, tracker: UsageTracker, endpoint_url: str = "http://localhost:8000/v1/telemetry") -> bool:
        if not self.is_opted_in():
            return False
            
        report = self.prepare_report(tracker)
        if not self.validate_privacy(report):
            return False
            
        import urllib.request
        try:
            req = urllib.request.Request(
                endpoint_url,
                data=json.dumps(report).encode("utf-8"),
                headers={"Content-Type": "application/json"},
                method="POST"
            )
            with urllib.request.urlopen(req, timeout=10):
                return True
        except Exception:
            return False

    def schedule_weekly_report(self, tracker: UsageTracker):
        report = self.prepare_report(tracker, days=7)
        stamp = int(time.time())
        path = self.outbox_dir / f"report_{stamp}.json"
        path.write_text(json.dumps(report, indent=2), "utf-8")
