"""
Purpose: Load and merge host configuration from YAML file with code parameters
LLM-Note:
  Dependencies: imports from [pathlib, yaml] | imported by [network/host/server.py] | no tests (simple utility)
  Data flow: load_host_config(co_dir, **code_params) → reads .co/host.yaml if exists → yaml.safe_load() → merges with code_params (code overrides YAML) → returns dict | load_list_file(path) → reads line-by-line → strips comments (#) → returns list of addresses
  State/Effects: reads .co/host.yaml from filesystem | reads whitelist/blacklist files | no writes | no persistent state
  Integration: exposes load_host_config(co_dir, **code_params), load_list_file(file_path) | used by host() function to merge configuration sources | code parameters take precedence over YAML
  Performance: simple file I/O | YAML parsing via safe_load | no caching (loads on each call)
  Errors: returns empty dict/list if file doesn't exist | YAML parsing errors bubble up

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
