#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
User Profile Store: UserProfile dataclass + ~/.pulse/profile.json persistence.

Single responsibility: load, save, and access user preferences.
Used by boot_formatting, bridge, and agents to personalize behavior.

Dependencies: Python stdlib only (Law 4)
"""

import json
import os
import shutil
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import List


def _profile_path() -> Path:
    """Return ~/.pulse/profile.json (global, not per-project)."""
    return Path.home() / ".pulse" / "profile.json"


@dataclass
class UserProfile:
    """User preferences persisted across sessions."""

    name: str = ""
    preferred_verbosity: str = "normal"  # minimal | normal | verbose
    preferred_format: str = "auto"  # auto | markdown | plain
    communication_style: str = "concise"  # concise | detailed | casual
    providers_detected: List[str] = field(default_factory=list)
    dont_wants: List[str] = field(default_factory=list)

    # --- persistence ---

    def save(self, path: Path = None) -> Path:
        """Write profile to JSON. Returns the path written."""
        p = path or _profile_path()
        p.parent.mkdir(parents=True, exist_ok=True)
        p.write_text(json.dumps(asdict(self), indent=2), encoding="utf-8")
        return p

    @classmethod
    def load(cls, path: Path = None) -> "UserProfile":
        """Load from JSON, returning defaults if file missing or corrupt."""
        p = path or _profile_path()
        if not p.exists():
            return cls()
        try:
            data = json.loads(p.read_text(encoding="utf-8"))
            # Only pass known fields to avoid TypeError on extra keys
            known = {f.name for f in cls.__dataclass_fields__.values()}
            return cls(**{k: v for k, v in data.items() if k in known})
        except (json.JSONDecodeError, TypeError):
            return cls()

    # --- convenience ---

    def detect_providers(self) -> List[str]:
        """Auto-detect available LLM providers and update list."""
        detected = []
        if os.environ.get("ANTHROPIC_API_KEY"):
            detected.append("anthropic")
        if os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY"):
            detected.append("google")
        if os.environ.get("OPENAI_API_KEY"):
            detected.append("openai")
        if shutil.which("ollama"):
            detected.append("ollama")
        self.providers_detected = detected
        return detected


def load_profile(path: Path = None) -> UserProfile:
    """Module-level shortcut: load or create default profile."""
    return UserProfile.load(path)


def save_profile(profile: UserProfile, path: Path = None) -> Path:
    """Module-level shortcut: save profile."""
    return profile.save(path)


if __name__ == "__main__":
    p = load_profile()
    p.detect_providers()
    dest = p.save()
    print(f"Profile at {dest}:")
    print(json.dumps(asdict(p), indent=2))
