"""Read and write antiqa.json project configuration."""

from __future__ import annotations

import json
from pathlib import Path

from .schema import AntiQAConfig

CONFIG_FILENAME = "antiqa.json"


def find_config_path(start: Path | None = None) -> Path:
    """Return the path to antiqa.json in the given (or current) directory."""
    root = start or Path.cwd()
    return root / CONFIG_FILENAME


def config_exists(start: Path | None = None) -> bool:
    return find_config_path(start).is_file()


def load_config(start: Path | None = None) -> AntiQAConfig:
    """Load and validate antiqa.json from *start* directory."""
    path = find_config_path(start)
    if not path.is_file():
        raise FileNotFoundError(
            f"No {CONFIG_FILENAME} found in {path.parent}. Run 'antiqa init' first."
        )
    raw = json.loads(path.read_text())
    return AntiQAConfig.model_validate(raw)


def save_config(config: AntiQAConfig, start: Path | None = None) -> Path:
    """Write validated config to antiqa.json and return the path."""
    path = find_config_path(start)
    path.write_text(
        json.dumps(config.model_dump(), indent=2) + "\n"
    )
    return path
