"""
Load host.yaml configuration file.

host.yaml is optional — generated by 'co init' or 'co create'.
Code parameters override YAML values.
"""

from pathlib import Path
import yaml


def load_host_config(co_dir: Path = None, **code_params) -> dict:
    """
    Load host configuration from .co/host.yaml.

    Priority (highest to lowest):
    1. Code parameters (passed to host())
    2. Config file (.co/host.yaml) — optional

    Args:
        co_dir: Path to .co directory (defaults to ./.co/)
        **code_params: Code parameters from host() function

    Returns:
        Config dict from YAML with code param overrides
    """
    if co_dir is None:
        co_dir = Path.cwd() / '.co'

    config = {}
    config_path = co_dir / 'host.yaml'
    if config_path.exists():
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f) or {}

    # Code params override YAML (only if not None)
    for key, value in code_params.items():
        if value is not None:
            config[key] = value

    return config


def load_list_file(file_path: str | Path | None) -> list:
    """
    Load addresses from whitelist/blacklist file.

    File format: one address per line, comments with #

    Args:
        file_path: Path to list file

    Returns:
        List of addresses (empty list if file doesn't exist)
    """
    if file_path is None:
        return []

    path = Path(file_path)
    if not path.exists():
        return []

    addresses = []
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if '#' in line:
                line = line[:line.index('#')].strip()
            if line:
                addresses.append(line)

    return addresses
