"""Agent configuration — load/save from ~/.easyclaw/agent.json."""

from __future__ import annotations

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

AGENT_DIR = Path.home() / ".easyclaw"
CONFIG_PATH = AGENT_DIR / "agent.json"
PID_PATH = AGENT_DIR / "agent.pid"
LOG_PATH = AGENT_DIR / "agent.log"

DEFAULT_MODEL = "moonshotai/kimi-k2.5"
_OLD_DEFAULT_MODEL = "anthropic/claude-3.5-haiku"
BUILTIN_OR_KEY = "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"


@dataclass
class AgentConfig:
    api_key: str = ""
    openrouter_key: str = ""
    model: str = DEFAULT_MODEL
    check_interval: int = 60
    max_auto_fix_attempts: int = 3
    log_level: str = "INFO"
    max_history: int = 40
    max_tool_iterations: int = 15

    # Runtime state (persisted)
    last_health_check: str = ""
    daemon_pid: int = 0
    recent_actions: list[dict[str, Any]] = field(default_factory=list)

    @classmethod
    def load(cls) -> AgentConfig:
        """Load config from disk, falling back to defaults."""
        if CONFIG_PATH.exists():
            try:
                data = json.loads(CONFIG_PATH.read_text())
                # Migrate old default model to new one
                model = data.get("model", DEFAULT_MODEL)
                if model == _OLD_DEFAULT_MODEL:
                    model = DEFAULT_MODEL
                return cls(
                    api_key=data.get("api_key", ""),
                    openrouter_key=data.get("openrouter_key", ""),
                    model=model,
                    check_interval=data.get("check_interval", 60),
                    max_auto_fix_attempts=data.get("max_auto_fix_attempts", 3),
                    log_level=data.get("log_level", "INFO"),
                    max_history=data.get("max_history", 40),
                    max_tool_iterations=data.get("max_tool_iterations", 15),
                    last_health_check=data.get("last_health_check", ""),
                    daemon_pid=data.get("daemon_pid", 0),
                    recent_actions=data.get("recent_actions", []),
                )
            except (json.JSONDecodeError, KeyError):
                pass
        instance = cls()
        # Migrate from old default model to new one
        if instance.model == _OLD_DEFAULT_MODEL:
            instance.model = DEFAULT_MODEL
        return instance

    def save(self) -> None:
        """Persist config to disk."""
        AGENT_DIR.mkdir(parents=True, exist_ok=True)
        CONFIG_PATH.write_text(json.dumps(asdict(self), indent=2))

    def resolve_keys(
        self,
        cli_api_key: str = "",
        cli_or_key: str = "",
    ) -> None:
        """Resolve API keys: CLI args > env vars > config file > install summary."""
        # EasyClaw API key
        if cli_api_key:
            self.api_key = cli_api_key
        elif os.environ.get("EASYCLAW_API_KEY"):
            self.api_key = os.environ["EASYCLAW_API_KEY"]
        elif not self.api_key:
            # Try install summary
            summary = Path.home() / ".openclaw" / "install-summary.txt"
            if summary.exists():
                for line in summary.read_text().splitlines():
                    if "easyclaw" in line.lower() and "api" in line.lower():
                        parts = line.split(":", 1)
                        if len(parts) == 2:
                            self.api_key = parts[1].strip()
                            break

        # OpenRouter key for Agent Johnny 5
        # Priority: CLI arg > agent-specific env var > built-in key
        # NOTE: We do NOT read OPENROUTER_API_KEY here — that env var
        # is set by OpenClaw for the gateway (often a free-tier key).
        # The agent has its own built-in paid key.
        if cli_or_key:
            self.openrouter_key = cli_or_key
        elif os.environ.get("EASYCLAW_OPENROUTER_KEY"):
            self.openrouter_key = os.environ["EASYCLAW_OPENROUTER_KEY"]
        elif not self.openrouter_key:
            self.openrouter_key = BUILTIN_OR_KEY
