"""
agentpaas.services.profile — Auto user profile building

Tracks: frequent commands, coding preferences, work hours, interaction style.
Auto-injected into agent system prompt on startup.
"""
from __future__ import annotations

import json
import os
import time
from typing import Any, Dict


PROFILE_PATH = os.path.expanduser("~/.lambdagent/user_profile.json")


class UserProfile:
    """Auto-building user profile."""

    def __init__(self, path: str = ""):
        self.path = path or PROFILE_PATH
        self.data: Dict[str, Any] = self._load()

    def _load(self) -> dict:
        if os.path.exists(self.path):
            try:
                with open(self.path) as f:
                    return json.load(f)
            except Exception:
                pass
        return {
            "user": {"name": "", "timezone": "", "locale": "zh-CN"},
            "coding": {"primary_language": "", "editor": "", "test_framework": ""},
            "interaction": {"verbosity": "medium", "language": "zh-CN",
                            "confirmed_tools": []},
            "frequent_commands": {},
            "frequent_paths": {},
            "updated_at": 0,
        }

    def save(self):
        self.data["updated_at"] = time.time()
        os.makedirs(os.path.dirname(self.path), exist_ok=True)
        with open(self.path, "w", encoding="utf-8") as f:
            json.dump(self.data, f, ensure_ascii=False, indent=2)

    def record_command(self, cmd: str):
        """Track frequently used commands."""
        cmds = self.data.setdefault("frequent_commands", {})
        key = cmd.split()[0] if cmd else ""
        if key:
            cmds[key] = cmds.get(key, 0) + 1
            self.save()

    def record_path(self, path: str):
        """Track frequently accessed paths."""
        paths = self.data.setdefault("frequent_paths", {})
        paths[path] = paths.get(path, 0) + 1
        self.save()

    def update(self, section: str, key: str, value: Any):
        """Update a profile field."""
        if section in self.data and isinstance(self.data[section], dict):
            self.data[section][key] = value
            self.save()

    def summary(self) -> str:
        """Generate a one-paragraph summary for system prompt injection."""
        parts = []
        u = self.data.get("user", {})
        if u.get("name"):
            parts.append(f"用户名: {u['name']}")
        if u.get("locale"):
            parts.append(f"语言: {u['locale']}")

        c = self.data.get("coding", {})
        if c.get("primary_language"):
            parts.append(f"主要编程语言: {c['primary_language']}")
        if c.get("editor"):
            parts.append(f"编辑器: {c['editor']}")

        cmds = self.data.get("frequent_commands", {})
        if cmds:
            top = sorted(cmds.items(), key=lambda x: -x[1])[:5]
            parts.append(f"常用命令: {', '.join(k for k,v in top)}")

        return "; ".join(parts) if parts else ""

    def to_dict(self) -> dict:
        return self.data


def profile_get(input_val: Any) -> str:
    """Get user profile."""
    p = UserProfile()
    return json.dumps(p.to_dict(), ensure_ascii=False, indent=2)


def profile_update(input_val: Any) -> str:
    """Update profile field. Input: {section, key, value}"""
    params = _parse(input_val)
    section = params.get("section", "")
    key = params.get("key", "")
    value = params.get("value", "")
    if not section or not key:
        return "[ERROR] section and key are required"
    p = UserProfile()
    p.update(section, key, value)
    return f"[OK] Profile updated: {section}.{key} = {value}"


def _parse(input_val: Any) -> dict:
    if isinstance(input_val, dict):
        return input_val
    if isinstance(input_val, str):
        try:
            return json.loads(input_val)
        except (json.JSONDecodeError, ValueError):
            return {}
    return {}
