"""
Starvex Templates - Pre-built industry compliance templates.

This module provides ready-to-use guardrail configurations for common
regulated industries. Each template bundles a curated set of rules
pre-configured to satisfy the relevant compliance standards.

Example:
    from starvex.templates import get_template, list_templates

    # See what is available
    print(list_templates())

    # Load a healthcare template and apply its rules
    template = get_template("healthcare")
    guard = StarvexGuard(rules=template.rules)
"""

import logging
from dataclasses import dataclass, field
from typing import Any, Dict, List

from starvex.guardrails.rules import (
    BlockJailbreak,
    BlockPII,
    BlockToxicity,
    CustomBlocklist,
    PolicyCompliance,
    TopicRestriction,
)

logger = logging.getLogger(__name__)

# ---------------------------------------------------------------------------
# Data model
# ---------------------------------------------------------------------------


@dataclass
class IndustryTemplate:
    """A pre-built guardrail configuration targeting a specific industry.

    Attributes:
        name: Short identifier for the template (e.g. ``"healthcare"``).
        description: Human-readable summary of what the template covers.
        industry: Industry category this template targets.
        rules: Pre-configured rule instances ready to pass to a guard.
        compliance_standards: Regulatory standards addressed by the template
            (e.g. ``["HIPAA"]``, ``["PCI DSS", "FINRA"]``).
    """

    name: str
    description: str
    industry: str
    rules: List  # List of GuardRule instances; untyped to avoid circular imports
    compliance_standards: List[str] = field(default_factory=list)


# ---------------------------------------------------------------------------
# Template factories
# ---------------------------------------------------------------------------


def healthcare_template() -> IndustryTemplate:
    """Return a HIPAA-oriented healthcare compliance template.

    Includes:
        * Strict PII detection (``score_threshold=0.3``) to catch PHI.
        * Jailbreak prevention.
        * Policy compliance rules aligned with HIPAA guidance.
        * Topic restrictions blocking ``medical_advice`` and ``legal_advice``.
        * Custom blocklist targeting common PHI patterns.

    Returns:
        An :class:`IndustryTemplate` configured for healthcare.
    """

    rules = [
        BlockPII(score_threshold=0.3),
        BlockJailbreak(),
        PolicyCompliance(
            policies=[
                "Never provide medical diagnoses",
                "Never recommend specific medications",
                "Always recommend consulting a healthcare provider",
                "Do not share patient information",
            ],
        ),
        TopicRestriction(blocked_topics=["medical_advice", "legal_advice"]),
        CustomBlocklist(
            patterns=[
                r"\b\d{3}-\d{2}-\d{4}\b",      # SSN pattern
                r"\b[A-Z]{2}\d{7,8}\b",          # Medical record number
                r"\bMRN\s*[:#]?\s*\d+\b",        # MRN prefix pattern
                r"\bDOB\s*[:#]?\s*\d{1,2}[/-]\d{1,2}[/-]\d{2,4}\b",  # Date of birth
            ],
            phrases=[
                "patient record",
                "medical history",
                "health insurance",
                "treatment plan",
            ],
        ),
    ]

    logger.debug("Created healthcare compliance template with %d rules", len(rules))

    return IndustryTemplate(
        name="healthcare",
        description=(
            "HIPAA-aligned template for healthcare applications. "
            "Blocks PHI leakage, prevents medical advice, and enforces "
            "strict PII detection thresholds."
        ),
        industry="Healthcare",
        rules=rules,
        compliance_standards=["HIPAA"],
    )


def finance_template() -> IndustryTemplate:
    """Return a financial-services compliance template.

    Covers FINRA, SEC, and PCI DSS requirements including:
        * Strict PII detection (``score_threshold=0.3``).
        * Jailbreak prevention.
        * Policy compliance rules forbidding investment advice and return
          guarantees.
        * Topic restrictions blocking ``investment_advice`` and
          ``legal_advice``.

    Returns:
        An :class:`IndustryTemplate` configured for financial services.
    """

    rules = [
        BlockPII(score_threshold=0.3),
        BlockJailbreak(),
        PolicyCompliance(
            policies=[
                "Never provide specific investment advice",
                "Always include risk disclaimers",
                "Never guarantee returns",
                "Do not process financial transactions",
            ],
        ),
        TopicRestriction(blocked_topics=["investment_advice", "legal_advice"]),
    ]

    logger.debug("Created finance compliance template with %d rules", len(rules))

    return IndustryTemplate(
        name="finance",
        description=(
            "Financial-services template covering FINRA, SEC, and PCI DSS. "
            "Prevents investment advice, enforces risk disclaimers, and "
            "applies strict PII detection for cardholder data."
        ),
        industry="Financial Services",
        rules=rules,
        compliance_standards=["FINRA", "SEC", "PCI DSS"],
    )


def legal_template() -> IndustryTemplate:
    """Return an attorney-client privilege compliance template.

    Includes:
        * PII detection (default threshold).
        * Jailbreak prevention.
        * Policy compliance rules preserving privilege and preventing
          unauthorized legal opinions.

    Returns:
        An :class:`IndustryTemplate` configured for legal services.
    """

    rules = [
        BlockPII(),
        BlockJailbreak(),
        PolicyCompliance(
            policies=[
                "Never provide legal advice or opinions",
                "Always recommend consulting a licensed attorney",
                "Do not interpret contracts or legal documents",
                "Maintain attorney-client privilege",
            ],
        ),
    ]

    logger.debug("Created legal compliance template with %d rules", len(rules))

    return IndustryTemplate(
        name="legal",
        description=(
            "Legal-services template designed to protect attorney-client "
            "privilege. Prevents unauthorized legal opinions and blocks "
            "document interpretation."
        ),
        industry="Legal",
        rules=rules,
        compliance_standards=["Attorney-Client Privilege"],
    )


def education_template() -> IndustryTemplate:
    """Return a FERPA- and COPPA-oriented education compliance template.

    Includes:
        * Strict PII detection (``score_threshold=0.3``) for student data.
        * Jailbreak prevention.
        * Toxicity filtering for age-appropriate content.
        * Policy compliance rules protecting minors and student records.

    Returns:
        An :class:`IndustryTemplate` configured for education.
    """

    rules = [
        BlockPII(score_threshold=0.3),
        BlockJailbreak(),
        BlockToxicity(),
        PolicyCompliance(
            policies=[
                "Do not collect personal information from minors",
                "Never share student records",
                "Ensure age-appropriate content",
            ],
        ),
    ]

    logger.debug("Created education compliance template with %d rules", len(rules))

    return IndustryTemplate(
        name="education",
        description=(
            "Education template aligned with FERPA and COPPA. "
            "Protects student records, blocks collection of minor data, "
            "and enforces age-appropriate content filtering."
        ),
        industry="Education",
        rules=rules,
        compliance_standards=["FERPA", "COPPA"],
    )


# ---------------------------------------------------------------------------
# Template registry
# ---------------------------------------------------------------------------

_TEMPLATE_REGISTRY: Dict[str, Any] = {
    "healthcare": healthcare_template,
    "finance": finance_template,
    "legal": legal_template,
    "education": education_template,
}


def get_template(name: str) -> IndustryTemplate:
    """Look up and return a pre-built industry template by name.

    Args:
        name: Case-insensitive template identifier (e.g. ``"healthcare"``).

    Returns:
        The corresponding :class:`IndustryTemplate`.

    Raises:
        ValueError: If *name* does not match any registered template.
    """

    key = name.strip().lower()
    factory = _TEMPLATE_REGISTRY.get(key)

    if factory is None:
        available = ", ".join(sorted(_TEMPLATE_REGISTRY.keys()))
        raise ValueError(
            f"Unknown template '{name}'. Available templates: {available}"
        )

    logger.info("Loading industry template: %s", key)
    return factory()


def list_templates() -> List[str]:
    """Return the names of all available industry templates.

    Returns:
        A sorted list of template name strings.
    """

    return sorted(_TEMPLATE_REGISTRY.keys())
