"""GENERATED by witgen — DO NOT EDIT.

Re-generate with: uv run python -m tools.witgen
"""

from __future__ import annotations

from typing import Any

# FIXME(wasmtime-py): v40 does not export Record/Variant from a public path;
# wasmtime.component._types is the only way to access them.  Revisit when
# wasmtime-py exposes a public API for component-model types.
from wasmtime.component._types import Record, Variant

from ._types import (
    AllowedBotConfig,
    AllowEmailValidationConfig,
    BotConfig,
    BotResult,
    DeniedBotConfig,
    DenyEmailValidationConfig,
    DetectedSensitiveInfoEntity,
    EmailValidationConfig,
    EmailValidationResult,
    Err,
    FilterResult,
    Ok,
    Result,
    SensitiveInfoConfig,
    SensitiveInfoEntities,
    SensitiveInfoEntitiesAllow,
    SensitiveInfoEntitiesDeny,
    SensitiveInfoEntity,
    SensitiveInfoEntityCreditCardNumber,
    SensitiveInfoEntityCustom,
    SensitiveInfoEntityEmail,
    SensitiveInfoEntityIpAddress,
    SensitiveInfoEntityPhoneNumber,
    SensitiveInfoResult,
)


def _rec(**kwargs: Any) -> Record:
    """Build a wasmtime Record with kebab-case attributes."""
    r = Record()
    r.__dict__.update(kwargs)
    return r


def to_wasm_bot_config(config: BotConfig) -> Variant:
    """Convert BotConfig union to a wasmtime Variant."""
    if isinstance(config, AllowedBotConfig):
        return Variant(
            "allowed-bot-config",
            _rec(entities=config.entities, **{"skip-custom-detect": config.skip_custom_detect}),
        )
    elif isinstance(config, DeniedBotConfig):
        return Variant(
            "denied-bot-config",
            _rec(entities=config.entities, **{"skip-custom-detect": config.skip_custom_detect}),
        )
    raise TypeError(f"Expected BotConfig, got {type(config).__name__}")


def to_wasm_email_validation_config(config: EmailValidationConfig) -> Variant:
    """Convert EmailValidationConfig union to a wasmtime Variant."""
    if isinstance(config, AllowEmailValidationConfig):
        return Variant(
            "allow-email-validation-config",
            _rec(**{"require-top-level-domain": config.require_top_level_domain}, **{"allow-domain-literal": config.allow_domain_literal}, allow=config.allow),
        )
    elif isinstance(config, DenyEmailValidationConfig):
        return Variant(
            "deny-email-validation-config",
            _rec(**{"require-top-level-domain": config.require_top_level_domain}, **{"allow-domain-literal": config.allow_domain_literal}, deny=config.deny),
        )
    raise TypeError(f"Expected EmailValidationConfig, got {type(config).__name__}")


def to_wasm_sensitive_info_entity(entity: SensitiveInfoEntity) -> Variant:
    """Convert a SensitiveInfoEntity to a wasmtime Variant."""
    if isinstance(entity, SensitiveInfoEntityEmail):
        return Variant("email")
    elif isinstance(entity, SensitiveInfoEntityPhoneNumber):
        return Variant("phone-number")
    elif isinstance(entity, SensitiveInfoEntityIpAddress):
        return Variant("ip-address")
    elif isinstance(entity, SensitiveInfoEntityCreditCardNumber):
        return Variant("credit-card-number")
    elif isinstance(entity, SensitiveInfoEntityCustom):
        return Variant("custom", entity.value)
    raise TypeError(f"Unknown SensitiveInfoEntity: {type(entity)}")


def to_wasm_sensitive_info_entities(entity: SensitiveInfoEntities) -> Variant:
    """Convert a SensitiveInfoEntities to a wasmtime Variant."""
    if isinstance(entity, SensitiveInfoEntitiesAllow):
        return Variant("allow", [to_wasm_sensitive_info_entity(e) for e in entity.entities])
    elif isinstance(entity, SensitiveInfoEntitiesDeny):
        return Variant("deny", [to_wasm_sensitive_info_entity(e) for e in entity.entities])
    raise TypeError(f"Unknown SensitiveInfoEntities: {type(entity)}")


def to_wasm_sensitive_info_config(config: SensitiveInfoConfig) -> Record:
    """Convert SensitiveInfoConfig to a wasmtime Record."""
    return _rec(
        entities=to_wasm_sensitive_info_entities(config.entities),
        **{"context-window-size": config.context_window_size},
        **{"skip-custom-detect": config.skip_custom_detect},
    )


def from_wasm_filter_result(raw: Any) -> FilterResult:
    """Convert a wasmtime Record to FilterResult."""
    try:
        return FilterResult(
            allowed=raw.allowed,
            matched_expressions=getattr(raw, "matched-expressions"),
            undetermined_expressions=getattr(raw, "undetermined-expressions"),
        )
    except AttributeError as exc:
        raise TypeError(f"failed to convert wasmtime Record to FilterResult: {exc}") from exc


def from_wasm_sensitive_info_entity(raw: Any) -> SensitiveInfoEntity:
    """Convert a wasmtime Variant to SensitiveInfoEntity."""
    if not isinstance(raw, Variant):
        raise TypeError(f"expected Variant for sensitive-info-entity, got {type(raw)}")
    tag = raw.tag
    if tag == "email":
        return SensitiveInfoEntityEmail()
    elif tag == "phone-number":
        return SensitiveInfoEntityPhoneNumber()
    elif tag == "ip-address":
        return SensitiveInfoEntityIpAddress()
    elif tag == "credit-card-number":
        return SensitiveInfoEntityCreditCardNumber()
    elif tag == "custom":
        return SensitiveInfoEntityCustom(str(raw.payload))
    raise ValueError(f"Unknown sensitive-info-entity tag: {tag}")


def from_wasm_detected_sensitive_info_entity(raw: Any) -> DetectedSensitiveInfoEntity:
    """Convert a wasmtime Record to DetectedSensitiveInfoEntity."""
    try:
        return DetectedSensitiveInfoEntity(
            start=raw.start,
            end=raw.end,
            identified_type=from_wasm_sensitive_info_entity(getattr(raw, "identified-type")),
        )
    except AttributeError as exc:
        raise TypeError(f"failed to convert wasmtime Record to DetectedSensitiveInfoEntity: {exc}") from exc


def from_wasm_sensitive_info_result(raw: Any) -> SensitiveInfoResult:
    """Convert a wasmtime Record to SensitiveInfoResult."""
    try:
        return SensitiveInfoResult(
            allowed=[from_wasm_detected_sensitive_info_entity(e) for e in raw.allowed],
            denied=[from_wasm_detected_sensitive_info_entity(e) for e in raw.denied],
        )
    except AttributeError as exc:
        raise TypeError(f"failed to convert wasmtime Record to SensitiveInfoResult: {exc}") from exc


def from_wasm_detect_bot(raw: Any) -> Result[BotResult, str]:
    """Convert detect-bot result."""
    if isinstance(raw, str):
        return Err(raw)
    try:
        return Ok(
            BotResult(
                allowed=raw.allowed,
                denied=raw.denied,
                verified=raw.verified,
                spoofed=raw.spoofed,
            )
        )
    except AttributeError as exc:
        raise TypeError(f"failed to convert wasmtime Record in detect-bot result: {exc}") from exc


def from_wasm_match_filters(raw: Any) -> Result[FilterResult, str]:
    """Convert match-filters result."""
    if isinstance(raw, str):
        return Err(raw)
    return Ok(from_wasm_filter_result(raw))


def from_wasm_generate_fingerprint(raw: Any) -> Result[str, str]:
    """Convert generate-fingerprint result."""
    if not isinstance(raw, Variant):
        raise TypeError(f"expected Variant from generate-fingerprint, got {type(raw)}")
    if not isinstance(raw.payload, str):
        raise TypeError(f"expected str payload in generate-fingerprint result, got {type(raw.payload)}")
    if raw.tag == "ok":
        return Ok(raw.payload)
    elif raw.tag == "err":
        return Err(raw.payload)
    raise ValueError(f"Unknown generate-fingerprint result tag: {raw.tag}")


def from_wasm_validate_characteristics(raw: Any) -> Result[None, str]:
    """Convert validate-characteristics result."""
    if raw is None:
        return Ok(None)
    if not isinstance(raw, str):
        raise TypeError(f"expected str error from validate-characteristics, got {type(raw)}")
    return Err(raw)


def from_wasm_is_valid_email(raw: Any) -> Result[EmailValidationResult, str]:
    """Convert is-valid-email result."""
    if isinstance(raw, str):
        return Err(raw)
    try:
        return Ok(
            EmailValidationResult(
                validity=raw.validity,
                blocked=raw.blocked,
            )
        )
    except AttributeError as exc:
        raise TypeError(f"failed to convert wasmtime Record in is-valid-email result: {exc}") from exc


def from_wasm_detect_sensitive_info(raw: Any) -> SensitiveInfoResult:
    """Convert detect-sensitive-info result (direct Record)."""
    return from_wasm_sensitive_info_result(raw)
