"""Configuration management for iseq-flow CLI."""

import json
from pathlib import Path
from typing import Any

from pydantic_settings import BaseSettings


class FlowConfig(BaseSettings):
    """CLI configuration with defaults."""

    # API endpoints
    api_url: str = "http://localhost:8002"  # file-service
    compute_url: str = "http://localhost:8005"  # compute-service

    # Zitadel OAuth settings
    zitadel_issuer: str = "https://zitadel.iflow.intelliseq.com"
    zitadel_client_id: str = "354511658992861447"  # CLI app with Device Code flow

    # Token storage
    keyring_service: str = "iseq-flow"

    model_config = {
        "env_prefix": "FLOW_",
        "env_file": ".env",
        "extra": "ignore",
    }


def get_config_path() -> Path:
    """Get path to config file."""
    config_dir = Path.home() / ".config" / "iseq-flow"
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir / "config.json"


def load_config() -> dict[str, Any]:
    """Load config from file."""
    config_path = get_config_path()
    if config_path.exists():
        return json.loads(config_path.read_text())
    return {}


def save_config(config: dict[str, Any]) -> None:
    """Save config to file."""
    config_path = get_config_path()
    config_path.write_text(json.dumps(config, indent=2))


def get_settings() -> FlowConfig:
    """Get settings with file overrides."""
    file_config = load_config()

    # Create settings, allowing file config to override defaults
    return FlowConfig(**file_config)
