from __future__ import annotations

from pathlib import Path
from typing import Literal

from pydantic import BaseModel

DEFAULT_CONFIG_PATH = Path.home() / ".outofthebox" / "config.json"


class ProviderConfig(BaseModel):
    provider_type: Literal["azure_openai", "openrouter"] = "azure_openai"
    # Azure OpenAI
    azure_endpoint: str = ""
    azure_deployment: str = ""
    azure_api_version: str = "2024-02-15-preview"
    # OpenRouter — API key is read from OPENROUTER_API_KEY env var, not stored here
    openrouter_model: str = ""


class Config(BaseModel):
    target: ProviderConfig = ProviderConfig()
    generator: ProviderConfig = ProviderConfig()
    judge: ProviderConfig = ProviderConfig()

    @classmethod
    def from_file(cls, path: Path = DEFAULT_CONFIG_PATH) -> Config:
        if not path.exists():
            raise FileNotFoundError(f"Config not found at {path}. Run 'Setup Config' first.")
        return cls.model_validate_json(path.read_text())

    def to_file(self, path: Path = DEFAULT_CONFIG_PATH) -> None:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(self.model_dump_json(indent=2))
