"""
Landing Page Content Generation Tool for AI Copywriting.

Provides structured output schemas for Pydantic AI agents to generate
validated landing page content that can be directly saved to Site.settings.

The schemas align with:
- TypeScript UI components (lightwave-ui)
- Django Site.settings JSONField (platform_site)
- Pydantic AI structured outputs (result_type)

Usage with Pydantic AI:
    from pydantic_ai import Agent
    from lightwave.ai.tools.landing_page import (
        LandingPageContent,
        get_landing_page_copywriter,
    )

    # Get agent with structured output
    agent = get_landing_page_copywriter()

    # Generate content for a tenant
    result = await agent.run(
        "Generate landing page content for createOS - a creative operating system",
        deps=LandingPageContext(
            tenant_domain="createos.io",
            brand_name="createOS",
            tagline="A creative life. Organized.",
        ),
    )

    # Result is a validated LandingPageContent object
    site.settings.update(result.output.to_site_settings())
    site.save()
"""

from __future__ import annotations

from pydantic import BaseModel, ConfigDict, Field

from lightwave.schema.pydantic.ui.components.marketing.faq import FAQItem
from lightwave.schema.pydantic.ui.components.marketing.features import FeatureItem

# =============================================================================
# CONTEXT (Input to Agent)
# =============================================================================


class LandingPageContext(BaseModel):
    """Context for landing page content generation.

    This is passed to the agent as deps, providing tenant info
    and brand context for personalized copy.
    """

    # Tenant identification (from URL pattern)
    tenant_domain: str = Field(..., description="Domain like createos.io or cineos.io")
    tenant_schema: str | None = Field(None, description="PostgreSQL schema name")

    # Brand context
    brand_name: str = Field(..., description="Brand name like 'createOS' or 'cineOS'")
    tagline: str | None = Field(None, description="Brand tagline")

    # Product context
    product_type: str | None = Field(
        None,
        description="Product type: subscription, ecommerce, portfolio, marketing",
    )
    target_audience: list[str] = Field(
        default_factory=list,
        description="Who the product is for",
    )

    # Voice guidance
    voice_model: str | None = Field(
        None,
        description="Primary voice model: rick_rubin, dhh, jony_ive, stripe, notion",
    )

    model_config = ConfigDict(extra="forbid")


# =============================================================================
# HERO SECTION (UI-aligned)
# =============================================================================


class HeroContent(BaseModel):
    """Hero section content aligned with BaseHeroProps.

    Field names match TypeScript:
        packages/lightwave-ui/src/types/generated/islands/hero.d.ts
    """

    eyebrow: str | None = Field(None, description="Small text above headline")
    headline: str | None = Field(None, description="Main headline text")
    headline2: str | None = Field(None, description="Second line of headline")
    text: str | None = Field(None, description="Emphasized/underlined text in headline")
    description: str | None = Field(None, description="Description/body text")
    primaryCtaText: str | None = Field(None, description="Primary CTA button text")
    primaryCtaHref: str | None = Field(None, description="Primary CTA link")
    secondaryCtaText: str | None = Field(None, description="Secondary CTA button text")
    secondaryCtaHref: str | None = Field(None, description="Secondary CTA link")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# FEATURES SECTION (UI-aligned)
# =============================================================================


class FeaturesContent(BaseModel):
    """Features section content aligned with FeaturesSectionProps.

    Field names match TypeScript:
        packages/lightwave-ui/src/types/generated/islands/features.d.ts
    """

    eyebrow: str | None = Field(None, description="Small text above heading")
    headline: str | None = Field(None, description="Section headline")
    description: str | None = Field(None, description="Section description")
    features: list[FeatureItem] = Field(
        default_factory=list,
        description="List of feature items (3-6 recommended)",
    )
    primaryCtaText: str | None = Field(None, description="Primary CTA text")
    primaryCtaHref: str | None = Field(None, description="Primary CTA link")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# FAQ SECTION (UI-aligned)
# =============================================================================


class FAQContent(BaseModel):
    """FAQ section content aligned with FAQSectionProps.

    Field names match TypeScript:
        packages/lightwave-ui/src/types/generated/islands/faq.d.ts
    """

    eyebrow: str | None = Field(None, description="Small text above heading")
    headline: str | None = Field(None, description="Section headline")
    description: str | None = Field(None, description="Section description")
    items: list[FAQItem] = Field(
        default_factory=list,
        description="List of FAQ items (5-10 recommended)",
    )
    contactText: str | None = Field(None, description="Contact link text")
    contactHref: str | None = Field(None, description="Contact link URL")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# CONTENT SECTIONS (UI-aligned)
# =============================================================================


class ContentSection(BaseModel):
    """Rich content section for pages like About, Philosophy.

    Aligned with ContentSectionSimple01Props and similar.
    """

    headline: str | None = Field(None, description="Section headline")
    description: str | None = Field(None, description="Section description/intro")
    bodyContent: str | None = Field(None, description="Rich HTML body content")
    icon: str | None = Field(None, description="Icon name (e.g., 'zap-fast')")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# PHILOSOPHY SECTION (Brand-specific)
# =============================================================================


class PhilosophyContent(BaseModel):
    """Product philosophy/values - stored in Site.settings.

    This is CMS data, not a UI component. It informs copywriting.
    """

    core_insight: str | None = Field(None, description="Core insight that drives the product")
    product_thesis: str | None = Field(None, description="Product thesis statement")
    anti_patterns: list[str] = Field(
        default_factory=list,
        description="What we explicitly avoid/reject (3-5 items)",
    )
    founding_principles: list[str] = Field(
        default_factory=list,
        description="References to founding principle IDs",
    )

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# AUDIENCE SECTION (Brand-specific)
# =============================================================================


class AudienceContent(BaseModel):
    """Target audience definition - stored in Site.settings.

    This is CMS data, not a UI component. It informs copywriting.
    """

    for_audience: list[str] = Field(
        default_factory=list,
        alias="for",
        description="Who this product is FOR (3-5 descriptions)",
    )
    not_for_audience: list[str] = Field(
        default_factory=list,
        alias="not_for",
        description="Who this product is NOT for - repel wrong audience (2-4 items)",
    )
    pain_points: list[str] = Field(
        default_factory=list,
        description="Pain points we address (3-5 items)",
    )
    transformation: str | None = Field(None, description="The transformation promise")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# VOICE SECTION (Brand-specific)
# =============================================================================


class VoiceContent(BaseModel):
    """Brand voice configuration - stored in Site.settings."""

    primary: str | None = Field(
        None,
        description="Primary voice model: rick_rubin, dhh, jony_ive, stripe, notion",
    )
    secondary: str | None = Field(None, description="Secondary voice model")
    emotional_target: str | None = Field(
        None,
        description="Target emotional response: clarity_and_calm, respect, confidence",
    )
    tone_attributes: list[str] = Field(
        default_factory=list,
        description="Tone attributes: warm, direct, considered, confident",
    )

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# BLOG SECTION (UI-aligned)
# =============================================================================


class BlogPostSummary(BaseModel):
    """Blog post summary for listing pages."""

    title: str = Field(..., description="Post title")
    excerpt: str | None = Field(None, description="Post excerpt/summary")
    slug: str | None = Field(None, description="URL slug")
    category: str | None = Field(None, description="Post category")
    author: str | None = Field(None, description="Author name")
    publishDate: str | None = Field(None, description="Publish date ISO string")
    imageUrl: str | None = Field(None, description="Featured image URL")
    imageAlt: str | None = Field(None, description="Image alt text")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


class BlogContent(BaseModel):
    """Blog section content aligned with blog components."""

    eyebrow: str | None = Field(None, description="Small text above heading")
    headline: str | None = Field(None, description="Section headline")
    description: str | None = Field(None, description="Section description")
    posts: list[BlogPostSummary] = Field(
        default_factory=list,
        description="List of blog post summaries",
    )
    viewAllText: str | None = Field(None, description="View all link text")
    viewAllHref: str | None = Field(None, description="View all link URL")

    model_config = ConfigDict(extra="forbid", populate_by_name=True)


# =============================================================================
# COMBINED LANDING PAGE CONTENT (Structured Output)
# =============================================================================


class LandingPageContent(BaseModel):
    """Complete landing page content for AI generation.

    This is the result_type for Pydantic AI structured outputs.
    All fields align with Site.settings and UI component props.

    Example:
        agent = Agent(
            "claude-sonnet-4-20250514",
            result_type=LandingPageContent,
            ...
        )
        result = await agent.run("Generate landing page for createOS")
        site.settings.update(result.output.to_site_settings())
    """

    # UI Component sections (variant-agnostic)
    hero: HeroContent = Field(default_factory=HeroContent, description="Hero section content")
    features: FeaturesContent = Field(
        default_factory=FeaturesContent,
        description="Features section content",
    )
    faq: FAQContent = Field(default_factory=FAQContent, description="FAQ section content")

    # Brand/CMS sections (stored in Site.settings)
    philosophy: PhilosophyContent = Field(
        default_factory=PhilosophyContent,
        description="Product philosophy",
    )
    audience: AudienceContent = Field(
        default_factory=AudienceContent,
        description="Target audience definition",
    )
    voice: VoiceContent = Field(default_factory=VoiceContent, description="Brand voice config")

    # Additional content sections
    content_sections: list[ContentSection] = Field(
        default_factory=list,
        description="Additional content sections (About, How it works, etc.)",
    )

    model_config = ConfigDict(extra="forbid", populate_by_name=True)

    def to_site_settings(self) -> dict:
        """Convert to Site.settings compatible format.

        Returns dict that can be used with:
            site.settings.update(content.to_site_settings())
        """
        return {
            "hero": self.hero.model_dump(by_alias=True, exclude_none=True),
            "features": self.features.model_dump(by_alias=True, exclude_none=True),
            "faq": self.faq.model_dump(by_alias=True, exclude_none=True),
            "philosophy": self.philosophy.model_dump(by_alias=True, exclude_none=True),
            "audience": self.audience.model_dump(by_alias=True, exclude_none=True),
            "voice": self.voice.model_dump(by_alias=True, exclude_none=True),
        }


# =============================================================================
# AGENT FACTORY
# =============================================================================


def get_landing_page_copywriter(model: str | None = None):
    """Get a Pydantic AI agent for landing page content generation.

    The agent outputs structured LandingPageContent that can be
    directly saved to Site.settings.

    Args:
        model: Model to use. Defaults to claude-sonnet-4-20250514.

    Returns:
        Pydantic AI Agent with result_type=LandingPageContent.

    Example:
        agent = get_landing_page_copywriter()
        result = await agent.run(
            "Generate landing page content for createOS",
            deps=LandingPageContext(
                tenant_domain="createos.io",
                brand_name="createOS",
                tagline="A creative life. Organized.",
            ),
        )
        print(result.output.hero.headline)  # "Creative Operating System"
    """
    from pydantic_ai import Agent

    from lightwave.ai.brand_context import get_brand_context
    from lightwave.ai.copywriter import _build_system_prompt

    agent_model = model or "claude-sonnet-4-20250514"
    context = get_brand_context()
    system_prompt = _build_system_prompt(context)

    landing_page_instructions = """
## Landing Page Generation

You are generating structured landing page content. Output JSON that matches
the LandingPageContent schema exactly.

### Hero Section Guidelines
- headline: 3-6 words, active voice, benefit-focused
- eyebrow: Optional context setter (product category or tagline)
- description: 1-2 sentences expanding on headline
- primaryCtaText: Action verb + benefit (e.g., "Start Free", "Get Started")
- secondaryCtaText: Lower commitment action (e.g., "Learn More", "See How")

### Features Section Guidelines
- 3-6 feature items
- Each feature: title (2-4 words), subtitle (1 sentence)
- Icons: message-chat-circle, zap, chart-breakout-square, users-01, etc.

### FAQ Section Guidelines
- 5-10 frequently asked questions
- Questions from customer perspective
- Answers: direct, helpful, 1-3 sentences

### Philosophy Section Guidelines
- core_insight: The "why" in one sentence
- product_thesis: What we believe about the problem
- anti_patterns: What we explicitly reject (list 3-5)

### Audience Section Guidelines
- for: Who this IS for (be specific, 3-5 items)
- not_for: Who this is NOT for (repel wrong audience, 2-4 items)
- pain_points: Problems we solve (3-5 items)
- transformation: Before → After in one line

### Voice Section Guidelines
- primary: rick_rubin, dhh, jony_ive, stripe, or notion
- emotional_target: clarity_and_calm, respect, or confidence
- tone_attributes: Choose 3-4 from [warm, direct, considered, confident, precise]
"""

    return Agent(
        agent_model,
        result_type=LandingPageContent,
        instructions=[system_prompt, landing_page_instructions],
        retries=2,
        deps_type=LandingPageContext,
    )


__all__ = [
    # Context
    "LandingPageContext",
    # Content sections
    "HeroContent",
    "FeaturesContent",
    "FAQContent",
    "ContentSection",
    "PhilosophyContent",
    "AudienceContent",
    "VoiceContent",
    "BlogContent",
    "BlogPostSummary",
    # Combined output
    "LandingPageContent",
    # Agent factory
    "get_landing_page_copywriter",
    # Re-exports for convenience
    "FeatureItem",
    "FAQItem",
]
