"""ASA project configuration (asa.config.json) loader and saver."""

from pathlib import Path
from typing import Literal

from pydantic import BaseModel

from .errors import ConfigNotFoundError
from .fs import safe_read_json, safe_write_json
from .paths import CONFIG_FILENAME


class LintConfig(BaseModel):
    maxFileLOC: int = 250
    warnFileLOC: int = 150
    strictBoundaries: bool = True


class DeployConfig(BaseModel):
    provider: str = "vercel"
    database: str = "supabase"
    region: str = "eu-central-1"


class AsaConfig(BaseModel):
    name: str
    version: str = "1.0.0"
    stack: str = "asa-native-v1"
    domains: list[str] = []
    modules: dict[str, str] = {}  # module_name → installed version
    deploy: DeployConfig = DeployConfig()
    lint: LintConfig = LintConfig()


def load_config(project_root: Path) -> AsaConfig:
    """Load asa.config.json from project root.

    Args:
        project_root: Path to project root.

    Returns:
        Parsed AsaConfig.

    Raises:
        ConfigNotFoundError: If config file doesn't exist.
    """
    config_path = project_root / CONFIG_FILENAME
    if not config_path.exists():
        raise ConfigNotFoundError(
            f"No {CONFIG_FILENAME} found at {project_root}. Run 'asa init' first."
        )
    data = safe_read_json(config_path)
    return AsaConfig(**data)


def save_config(config: AsaConfig, project_root: Path) -> None:
    """Save AsaConfig to asa.config.json.

    Args:
        config: Configuration to save.
        project_root: Path to project root.
    """
    config_path = project_root / CONFIG_FILENAME
    safe_write_json(config_path, config.model_dump(), overwrite=True)
