from pydantic import BaseModel, validator, Field
from typing import List, Dict, Any, Union, Literal, Optional
import re


class Rule(BaseModel):
    """Schema for a preprocessing rule"""

    action: Literal[
        "lower",
        "upper",
        "strip",
        "collapse_ws",
        "remove_punctuation",
        "to_ascii",
        "normalize_unicode",
        "slice",
        "regex_replace",
        "remove_html",
        "normalize_company",
        "normalize_phone",
        "extract_domain",
        "normalize_url",
    ]
    columns: Union[List[str], Literal["__ALL_STRINGS__"]]
    params: Optional[Dict[str, Any]] = Field(default_factory=dict)
    output_suffix: Optional[str] = None
    skip_errors: bool = False

    @validator("params")
    def validate_params(cls, v, values):
        """Validate parameters based on action type"""
        action = values.get("action")

        if action == "slice":
            if "start" in v and v["start"] is not None and v["start"] < 0:
                raise ValueError("Slice indices must be non-negative")
        elif action == "regex_replace":
            if "pattern" not in v:
                raise ValueError("regex_replace requires 'pattern' parameter")
            try:
                re.compile(v["pattern"])
            except re.error as e:
                raise ValueError(f"Invalid regex pattern: {e}")

        return v
