"""
Utilities for working with ParametersSchema: field extraction, validation, defaults, and threshold/color evaluation.
"""

from typing import Any, Optional
from hil_testbench.data_structs.parameters import ParametersSchema, ParameterField


def get_schema_fieldnames(schema: Optional[ParametersSchema]) -> list[str]:
    """Extract field names from ParametersSchema."""
    if not schema:
        return []
    return [f.name for f in schema.fields]


def validate_event_schema(
    event: dict[str, Any], schema: Optional[ParametersSchema], strict: bool = True
) -> bool:
    """Validate event dict against schema. If strict, raise ValueError; else warn and return False."""
    if not schema:
        return True
    schema_fields = get_schema_fieldnames(schema)
    for field in event.keys():
        if field not in schema_fields:
            msg = f"Unknown field '{field}' not in schema."
            if strict:
                raise ValueError(msg)
            else:
                # Import here to avoid circular dependency
                from hil_testbench.run.task_logger import (  # hil: allow-lazy - avoid circular import
                    TaskLogger,
                )

                logger = TaskLogger()
                logger.console_print(f"[SchemaValidation] Warning: {msg}", "WARNING")
                return False
    return True


def evaluate_thresholds(value: Any, field: ParameterField) -> Optional[str]:
    """Evaluate value against field thresholds, return color (as str) if matched."""
    for threshold in field.thresholds.values():
        mode = threshold.mode
        try:
            color = str(threshold.color) if threshold.color is not None else None
            if mode == "lt" and value < threshold.value:
                return color
            elif mode == "gt" and value > threshold.value:
                return color
            elif mode == "eq" and value == threshold.value:
                return color
            elif (
                mode == "range"
                and isinstance(threshold.value, tuple)
                and threshold.value[0] <= value <= threshold.value[1]
            ):
                return color
        except (TypeError, ValueError):
            continue
    return None
