"""Config loading and option resolution.

Resolution order: CLI flag > env var > config.toml > built-in default.
"""

import os
from pathlib import Path

try:
    import tomllib
except ImportError:
    import tomli as tomllib  # type: ignore[no-redef]


DEFAULTS = {
    "keypair": "~/.corpo/keypair.json",
    "api_url": "https://api.corpo.dev",
    "rpc_url": "https://api.devnet.solana.com",
    "program_id": "GTesTBiEWE32WHXXE2S4XbZvA5CrEc4xs6ZgRe895dP",
    "realm": "",
    "governance": "",
    "governing_token_mint": "",
}


def load_config(path: str | Path | None = None) -> dict:
    """Load config from a TOML file, returning a flat dict of resolved values."""
    if path is None:
        path = Path("~/.corpo/config.toml").expanduser()
    else:
        path = Path(path).expanduser()

    config: dict = {}
    if path.exists():
        with open(path, "rb") as f:
            raw = tomllib.load(f)
        # Flatten sections into a single dict
        for section in raw.values():
            if isinstance(section, dict):
                config.update(section)
    return config


def resolve(
    cli_value: str | None,
    env_name: str,
    config: dict,
    config_key: str,
    default: str = "",
) -> str:
    """Resolve a value using the precedence chain: CLI > env > config > default."""
    if cli_value is not None and cli_value != "":
        return cli_value
    env_val = os.environ.get(env_name, "")
    if env_val:
        return env_val
    conf_val = config.get(config_key, "")
    if conf_val:
        return str(conf_val)
    return default
