#!/usr/bin/env python3
"""Configuration management for ai-input-output.

Single source of truth: Pydantic BaseModel with defaults.
Priority: CLI args > Environment variables > Config file > Defaults
"""
import os
import yaml
from pathlib import Path
from pydantic import BaseModel


# Config file location
CONFIG_FILE = Path.home() / ".ai-input-output"


class AIOConfig(BaseModel):
    """Single source of truth for all configuration defaults."""
    model: str = "ollama/llama3.2"
    max_lines: int = 100
    max_chars: int = 4000
    reasoning_effort: str | None = None  # None, "low", "medium", "high" for reasoning models


def load_config() -> AIOConfig:
    """Load configuration from file or return defaults.
    
    Returns:
        AIOConfig with values from config file or defaults
    """
    if CONFIG_FILE.exists():
        try:
            with open(CONFIG_FILE, 'r') as f:
                data = yaml.safe_load(f) or {}
            return AIOConfig(**data)
        except Exception as e:
            import sys
            print(f"Warning: Could not load config file: {e}", file=sys.stderr)
    
    return AIOConfig()


def init_config_file(force: bool = False) -> bool:
    """Create config file with defaults.
    
    Args:
        force: If True, overwrite existing config file
        
    Returns:
        True if config was created/updated, False if already exists
    """
    if CONFIG_FILE.exists() and not force:
        return False
    
    # Dump default config to YAML
    config = AIOConfig()
    with open(CONFIG_FILE, 'w') as f:
        yaml.dump(config.model_dump(), f, default_flow_style=False, sort_keys=False)
    
    return True
