"""Configuration helpers for CLI defaults."""

from __future__ import annotations

import os
from pathlib import Path
import tomllib
from typing import cast

from platformdirs import user_config_path

from revo_module_installer.constants import (
    REGISTRY_REPOSITORY_URL,
    REGISTRY_URL_ENVIRONMENT_VARIABLE,
)


def get_default_config_path() -> Path:
    """Return the default path to the CLI configuration file.

    Returns:
        Default configuration file path.
    """
    config_root: Path = user_config_path("revo-modules", ensure_exists=False)
    return config_root / "config.toml"


def load_registry_url_from_config(config_path: Path) -> str | None:
    """Load the registry URL from a config file if present.

    Args:
        config_path: Path to the configuration file.

    Returns:
        Registry URL when configured, otherwise None.
    """
    if not config_path.is_file():
        return None

    config_bytes: bytes = config_path.read_bytes()
    config_text: str = config_bytes.decode("utf-8")
    try:
        config_data: dict[str, object] = tomllib.loads(config_text)
    except tomllib.TOMLDecodeError:
        return None

    registry_section: object = config_data.get("registry")
    if not isinstance(registry_section, dict):
        return None

    registry_section_data: dict[str, object] = cast(
        dict[str, object],
        registry_section,
    )
    registry_url_value: object = registry_section_data.get("url")
    if not isinstance(registry_url_value, str):
        return None

    normalized_url: str = registry_url_value.strip()
    if not normalized_url:
        return None

    return normalized_url


def get_default_registry_url() -> str:
    """Resolve the default registry URL from env, config, or fallback.

    Returns:
        Registry URL to use by default.
    """
    environment_override: str | None = os.getenv(REGISTRY_URL_ENVIRONMENT_VARIABLE)
    if environment_override:
        return environment_override

    config_path: Path = get_default_config_path()
    config_override: str | None = load_registry_url_from_config(config_path)
    if config_override:
        return config_override

    return REGISTRY_REPOSITORY_URL
