"""Form data validation."""

from __future__ import annotations

import re
from typing import Any

from corpo.forms.definitions import FormDefinition, FormField


def validate_field(field: FormField, value: Any) -> str | None:
    """Validate a single field value. Returns error message or None."""
    # Required check
    if field.required and (value is None or value == ""):
        return f"{field.label} is required."

    # Skip further checks if empty and not required
    if value is None or value == "":
        return None

    if field.type == "string":
        if not isinstance(value, str):
            return f"{field.label} must be a string."
        # LAO suffix validation for entity_name
        if field.id == "entity_name":
            return _validate_entity_name(value)

    elif field.type == "choice":
        if field.options and str(value) not in field.options:
            return f"{field.label} must be one of: {', '.join(field.options)}"

    elif field.type == "integer":
        try:
            int_val = int(value)
        except (ValueError, TypeError):
            return f"{field.label} must be an integer."
        if int_val <= 0:
            return f"{field.label} must be a positive integer."

    elif field.type == "percentage":
        try:
            pct = int(value)
        except (ValueError, TypeError):
            return f"{field.label} must be an integer percentage."
        if not field.required and pct == 0:
            pass  # 0 is valid for optional percentage fields (e.g., donation)
        elif not (1 <= pct <= 100):
            return f"{field.label} must be between 1 and 100."

    return None


def _validate_entity_name(name: str) -> str | None:
    """Validate entity name has LAO suffix."""
    upper = name.strip().upper()
    # Must end with LAO LLC or LAO L.L.C.
    if upper.endswith("LAO LLC") or upper.endswith("LAO L.L.C."):
        return None
    # Reject DAO suffix
    if "DAO" in upper:
        return "Entity names must use 'LAO' (not 'DAO'). Example: 'Alpine LAO LLC'"
    return "Entity name must end in 'LAO LLC' or 'LAO L.L.C.' — e.g. 'Alpine LAO LLC'"


def validate_form_data(form: FormDefinition, data: dict) -> list[dict]:
    """Validate all fields in a form. Returns list of error dicts."""
    errors = []
    for section in form.sections:
        for field in section.fields:
            value = data.get(field.id, field.default)
            err = validate_field(field, value)
            if err:
                errors.append({"field": field.id, "section": section.id, "error": err})
    return errors
