import yaml
from ..column import Column
from ..schema import Schema
from typing import Dict, Any

# Map type names (strings in YAML) to python types
_TYPE_MAP = {
    "int": int,
    "integer": int,
    "float": float,
    "double": float,
    "str": str,
    "string": str,
    "bool": bool,
    "boolean": bool,
}


def _resolve_type(type_value):
    if isinstance(type_value, str):
        t = _TYPE_MAP.get(type_value.lower())
        if t is None:
            raise ValueError(f"Unknown type name in schema: {type_value}")
        return t
    return type_value  # assume it's already a python type

def load_schema_from_yaml(path: str) -> Schema:
    """
    Load schema YAML and return a Schema object.
    Example YAML:
    version: "1.0"
    columns:
      order_id:
        type: int
        not_null: true
        unique: true
      amount:
        type: float
        min: 0
        max: 10000
      email:
        type: string
        regex: ".+@.+\\.com"
    """
    with open(path, "r", encoding="utf-8") as fh:
        data = yaml.safe_load(fh)

    version = str(data.get("version", "0"))
    cols = []
    for name, cfg in data.get("columns", {}).items():
        dtype = _resolve_type(cfg.get("type", "string"))
        col = Column(
            name=name,
            dtype=dtype,
            not_null=bool(cfg.get("not_null", False)),
            unique=bool(cfg.get("unique", False)),
            min_value=cfg.get("min", None),
            max_value=cfg.get("max", None),
            regex=cfg.get("regex", None),
        )
        cols.append(col)

    return Schema(version=version, columns=cols)
