# -*- coding: utf-8 -*-

from dataclasses import dataclass
import os
import re
from typing import Any

import yaml



@dataclass
class Config:
    token: str
    server_url: str
    default_room: str


def yaml_config_parser(
    path: str
) -> dict[str, Any]:
    """Private method for parsing YML config with env substitution.

    Args:
        path (str): Path to config.yml

    Raises:
        ImportError: If pyyaml not installed
        FileNotFoundError: If file not found
        ValueError: If invalid YAML

    Returns:
        dict[str, Any]: Parsed YAML section with environment variable substitution.
    """
    pattern = re.compile(r"\$\{([^}^{]+)\}")

    # FIXME: Refactor
    def _env_constructor(loader, node):
        value = loader.construct_scalar(node)
        for var in pattern.findall(value):
            env_value = os.getenv(var)
            if env_value is None:
                raise ValueError(f"Environment variable '{var}' not set")
            value = value.replace(f"${{{var}}}", env_value)
        return value

    yaml.SafeLoader.add_implicit_resolver("!env", pattern, None)
    yaml.SafeLoader.add_constructor("!env", _env_constructor)

    try:
        with open(path) as file:
            config = yaml.safe_load(file)
        if not config:
            return {}
        return config["screeps"]
    except FileNotFoundError:
        raise FileNotFoundError(f"YAML config file not found at: {path}")
    except yaml.YAMLError as e:
        raise ValueError(f"Error parsing YAML file: {e}")