"""Config file management for ComplyForm.

Resolution order: CLI --config flag -> COMPLYFORM_CONFIG env var ->
~/.complyform/config.yaml.
"""

from __future__ import annotations

import os
from pathlib import Path

import yaml
from pydantic import BaseModel, ConfigDict


class ComplyFormConfig(BaseModel):
    """ComplyForm configuration model."""

    model_config = ConfigDict(strict=True)

    # User preferences (preserved on deactivate)
    default_cloud: str | None = None
    default_format: str = "terminal"
    color: bool = True
    cache_ttl_hours: int = 24
    telemetry: bool = False
    corpus_contribution: bool = False
    github_token: str | None = None
    anthropic_api_key: str | None = None
    api_key: str | None = None

    # License state (system-managed, cleared on deactivate)
    license_key_hash: str | None = None
    tier: str = "community"
    license_expiry: str | None = None


def resolve_config_path(cli_path: str | None = None) -> Path:
    """CLI flag -> COMPLYFORM_CONFIG env -> ~/.complyform/config.yaml."""
    if cli_path is not None:
        return Path(cli_path)
    env_path = os.environ.get("COMPLYFORM_CONFIG")
    if env_path is not None:
        return Path(env_path)
    return Path.home() / ".complyform" / "config.yaml"


def ensure_complyform_dir() -> Path:
    """Create ~/.complyform/ with 0o700 permissions if missing."""
    config_dir = Path.home() / ".complyform"
    if not config_dir.exists():
        config_dir.mkdir(mode=0o700, parents=True)
    return config_dir


def load_config(config_path: Path) -> ComplyFormConfig:
    """Load YAML config. Create dir + default config on first run."""
    if not config_path.exists():
        ensure_complyform_dir()
        cfg = ComplyFormConfig()
        save_config(cfg, config_path)
        return cfg

    raw = config_path.read_text(encoding="utf-8")
    data = yaml.safe_load(raw)
    if data is None:
        return ComplyFormConfig()
    return ComplyFormConfig.model_validate(data)


def save_config(config: ComplyFormConfig, config_path: Path) -> None:
    """Atomic write: write to .tmp, then os.replace()."""
    config_path.parent.mkdir(parents=True, exist_ok=True)
    data = config.model_dump(mode="json", exclude_none=True)
    tmp_path = config_path.with_suffix(".tmp")
    tmp_path.write_text(
        yaml.dump(data, default_flow_style=False),
        encoding="utf-8",
    )
    os.chmod(tmp_path, 0o600)
    os.replace(tmp_path, config_path)
