"""Configuration management for Whisper Scribe."""

import os
import json
from pathlib import Path
from typing import Optional
from pydantic import BaseModel


def get_config_dir() -> Path:
    """Get the configuration directory."""
    config_dir = Path.home() / ".whisper-scribe"
    config_dir.mkdir(parents=True, exist_ok=True)
    return config_dir


def get_config_file() -> Path:
    """Get the configuration file path."""
    return get_config_dir() / "config.json"


def get_default_output_dir() -> Path:
    """Get the default output directory."""
    output_dir = get_config_dir() / "transcriptions"
    output_dir.mkdir(parents=True, exist_ok=True)
    return output_dir


def get_temp_dir() -> Path:
    """Get the temporary directory for downloads."""
    temp_dir = get_config_dir() / "temp"
    temp_dir.mkdir(parents=True, exist_ok=True)
    return temp_dir


class AppConfig(BaseModel):
    """Application configuration."""
    openai_api_key: str = ""
    output_directory: str = ""

    def __init__(self, **data):
        super().__init__(**data)
        if not self.output_directory:
            self.output_directory = str(get_default_output_dir())


def load_config() -> AppConfig:
    """Load configuration from file or environment."""
    config = AppConfig()
    config_file = get_config_file()

    # Try to load from config file
    if config_file.exists():
        try:
            with open(config_file, 'r') as f:
                data = json.load(f)
                config = AppConfig(**data)
        except (json.JSONDecodeError, Exception):
            pass

    # Environment variables override file config
    if os.environ.get("OPENAI_API_KEY"):
        config.openai_api_key = os.environ["OPENAI_API_KEY"]

    if os.environ.get("WHISPER_SCRIBE_OUTPUT_DIR"):
        config.output_directory = os.environ["WHISPER_SCRIBE_OUTPUT_DIR"]

    return config


def save_config(config: AppConfig) -> None:
    """Save configuration to file."""
    config_file = get_config_file()
    with open(config_file, 'w') as f:
        json.dump(config.model_dump(), f, indent=2)


def get_output_directory() -> Path:
    """Get the output directory, creating it if needed."""
    config = load_config()
    output_dir = Path(config.output_directory)
    output_dir.mkdir(parents=True, exist_ok=True)
    return output_dir


def get_api_key() -> str:
    """Get the OpenAI API key."""
    return load_config().openai_api_key
