"""
Blueprint Engine — aura_core extraction of app/services/blueprint.py

Defines 16 site section types, 4 depth presets, validation,
prompt spec generation, and completeness scoring.

Zero imports from app/. Typed Pydantic I/O for MCP exposure.
"""
import copy
from typing import Optional

from aura_core.module_contract import aura_module, ModuleResult
from aura_core.types import (
    BlueprintInput,
    BlueprintConfig,
    BlueprintValidation,
    SectionDefinition,
    FieldDefinition,
)

SECTION_CATEGORIES = {
    "core": {"label": "Core Sections", "description": "Essential sections every site needs", "color": "#4F46E5"},
    "persuasion": {"label": "Persuasion", "description": "Build desire and address objections", "color": "#7C3AED"},
    "trust": {"label": "Trust & Proof", "description": "Build credibility and social proof", "color": "#10B981"},
    "conversion": {"label": "Conversion", "description": "Drive visitors to take action", "color": "#F59E0B"},
    "showcase": {"label": "Showcase", "description": "Display work, products, or portfolio", "color": "#06B6D4"},
    "content": {"label": "Content", "description": "Educational content and resources", "color": "#EC4899"},
}

_RAW_SECTIONS = [
    {
        "key": "hero", "label": "Hero Section",
        "description": "Above-the-fold section with headline, subheadline, hero body text, and primary CTA button",
        "enabled": True, "required": True, "category": "core",
        "fields": [
            {"key": "headline", "label": "Headline", "type": "text", "description": "Powerful main headline (5-12 words)", "min_length": 20, "max_length": 120},
            {"key": "subheadline", "label": "Subheadline", "type": "text", "description": "Supporting subheadline that clarifies the value", "min_length": 30, "max_length": 200},
            {"key": "hero_body", "label": "Hero Body", "type": "textarea", "description": "3-5 sentences for the hero section that immediately communicates value and creates emotional connection", "min_length": 100, "max_length": 600},
            {"key": "cta_text", "label": "CTA Button Text", "type": "text", "description": "Action-oriented button text (2-5 words)", "min_length": 5, "max_length": 40},
            {"key": "cta_secondary_text", "label": "Secondary CTA Text", "type": "text", "description": "Secondary action text (e.g. 'Learn More')", "min_length": 0, "max_length": 40},
        ],
        "visual_options": {"background": "image|gradient|video", "overlay": True, "trust_badge": True, "animation": "fade-in|slide-up|none"},
        "ai_instructions": "Create a compelling above-the-fold hero section. The headline must stop scrolling. The subheadline must clarify the value proposition. The hero body must build desire and credibility. The CTA must be action-oriented and specific (never 'Submit' or 'Click Here').",
        "order": 0,
    },
    {
        "key": "problem", "label": "Problem Statement",
        "description": "Calls out the visitor's pain point clearly and empathetically to establish relevance",
        "enabled": True, "required": False, "category": "persuasion",
        "fields": [
            {"key": "problem_title", "label": "Section Title", "type": "text", "description": "Heading that names the problem", "min_length": 10, "max_length": 100},
            {"key": "problem_body", "label": "Problem Description", "type": "textarea", "description": "2-3 paragraphs describing frustrations the audience faces, using empathetic language", "min_length": 150, "max_length": 800},
            {"key": "problem_points", "label": "Pain Points", "type": "list", "description": "3-5 specific pain points as bullet items", "min_items": 3, "max_items": 5},
        ],
        "visual_options": {"style": "dark-bg|light-bg|gradient", "icons": True, "animation": "fade-in|slide-up|none"},
        "ai_instructions": "Articulate the core problem the target audience faces. Be specific, empathetic, and use language the audience would use themselves. Name real frustrations, not generic ones. This builds the 'before' picture.",
        "order": 1,
    },
    {
        "key": "solution", "label": "Solution / Value Proposition",
        "description": "Presents the offer as the clear answer to the problem stated above",
        "enabled": True, "required": False, "category": "persuasion",
        "fields": [
            {"key": "solution_title", "label": "Section Title", "type": "text", "description": "Heading that introduces the solution", "min_length": 10, "max_length": 100},
            {"key": "solution_body", "label": "Solution Description", "type": "textarea", "description": "3-4 paragraphs explaining how you solve the problem and why your approach is different", "min_length": 200, "max_length": 1000},
            {"key": "solution_points", "label": "Key Benefits", "type": "list", "description": "3-5 specific benefits (not features)", "min_items": 3, "max_items": 6},
        ],
        "visual_options": {"style": "light-bg|gradient|split-layout", "icons": True, "image": True},
        "ai_instructions": "Present the solution as the obvious answer. Focus on BENEFITS not features. Show the transformation - what life looks like AFTER using this. Be concrete and specific.",
        "order": 2,
    },
    {
        "key": "about", "label": "About / Our Story",
        "description": "Brand story section that builds trust and emotional connection",
        "enabled": True, "required": True, "category": "core",
        "fields": [
            {"key": "about_title", "label": "Section Title", "type": "text", "description": "Custom about section heading", "min_length": 5, "max_length": 80},
            {"key": "about", "label": "About Content", "type": "textarea", "description": "5-8 sentences telling the brand story - who you are, why you exist, what drives you", "min_length": 200, "max_length": 1200},
            {"key": "mission_statement", "label": "Mission Statement", "type": "text", "description": "One-line mission statement", "min_length": 20, "max_length": 200},
        ],
        "visual_options": {"style": "centered|split-image|timeline", "image": True},
        "ai_instructions": "Tell a compelling brand story. Include the WHY behind the brand. Make it personal and authentic. Include a clear mission statement. The reader should trust and respect the people behind this brand.",
        "order": 3,
    },
    {
        "key": "features", "label": "Features / What We Offer",
        "description": "Grid of features or services with icons, titles, and descriptions",
        "enabled": True, "required": True, "category": "core",
        "fields": [
            {"key": "offer", "label": "Section Introduction", "type": "textarea", "description": "2-3 sentences introducing the features section", "min_length": 50, "max_length": 400},
            {"key": "features", "label": "Feature Cards", "type": "card_list", "description": "6 feature cards with title, description (2-3 sentences each), and icon", "min_items": 4, "max_items": 9,
             "card_fields": [{"key": "title", "label": "Title", "type": "text"}, {"key": "description", "label": "Description", "type": "textarea"}, {"key": "icon", "label": "Icon", "type": "icon_select"}]},
        ],
        "visual_options": {"layout": "grid-3|grid-2|alternating|list", "card_style": "elevated|flat|bordered|gradient", "icons": True, "animation": "stagger-fade|slide-up|none"},
        "ai_instructions": "Generate 6 detailed feature cards. Each must have a unique icon, a specific title, and a 2-3 sentence description that explains the real value. Avoid generic phrases like 'state-of-the-art' or 'cutting-edge'. Be concrete.",
        "order": 4,
    },
    {
        "key": "how_it_works", "label": "How It Works",
        "description": "Step-by-step process showing how the product/service works",
        "enabled": True, "required": False, "category": "conversion",
        "fields": [
            {"key": "how_title", "label": "Section Title", "type": "text", "description": "Heading for the process section", "min_length": 10, "max_length": 80},
            {"key": "how_subtitle", "label": "Section Subtitle", "type": "text", "description": "Brief explanation of the process", "min_length": 20, "max_length": 200},
            {"key": "how_steps", "label": "Process Steps", "type": "card_list", "description": "3-5 numbered steps showing the process", "min_items": 3, "max_items": 6,
             "card_fields": [{"key": "title", "label": "Step Title", "type": "text"}, {"key": "description", "label": "Step Description", "type": "textarea"}, {"key": "icon", "label": "Icon", "type": "icon_select"}]},
        ],
        "visual_options": {"layout": "numbered-vertical|horizontal-timeline|alternating-zigzag", "connector_lines": True, "animation": "scroll-reveal|stagger|none"},
        "ai_instructions": "Create a clear step-by-step process. Each step must be actionable and specific. Use numbered steps with clear titles. The process should feel simple and achievable, reducing friction and building confidence.",
        "order": 5,
    },
    {
        "key": "stats", "label": "Statistics / Social Proof Numbers",
        "description": "Key metrics and numbers that build credibility",
        "enabled": True, "required": False, "category": "trust",
        "fields": [
            {"key": "stats", "label": "Statistics", "type": "card_list", "description": "4 impressive statistics with labels", "min_items": 3, "max_items": 6,
             "card_fields": [{"key": "value", "label": "Value", "type": "text"}, {"key": "label", "label": "Label", "type": "text"}, {"key": "description", "label": "Context", "type": "text"}]},
        ],
        "visual_options": {"layout": "bar|cards|inline", "animation": "count-up|fade-in|none", "position": "below-hero|standalone"},
        "ai_instructions": "Generate 4 realistic, impressive statistics that build credibility. Each stat needs a bold value, a clear label, and brief context. Numbers should be plausible for the niche. Use specific numbers (not round numbers) for authenticity.",
        "order": 6,
    },
    {
        "key": "testimonials", "label": "Testimonials",
        "description": "Customer quotes with names and roles that build social proof",
        "enabled": True, "required": True, "category": "trust",
        "fields": [
            {"key": "testimonials", "label": "Testimonial Cards", "type": "card_list", "description": "3-5 realistic testimonials from representative customers", "min_items": 3, "max_items": 6,
             "card_fields": [{"key": "quote", "label": "Quote", "type": "textarea"}, {"key": "name", "label": "Name", "type": "text"}, {"key": "role", "label": "Role/Title", "type": "text"}]},
        ],
        "visual_options": {"layout": "grid|carousel|featured", "card_style": "minimal|photo-avatar|branded", "stars": True},
        "ai_instructions": "Write 4 realistic testimonials. Each must sound authentic - use natural language, mention specific results or experiences, and include realistic names and roles. Avoid hyperbolic praise. Include diverse perspectives (different use cases, roles, demographics).",
        "order": 7,
    },
    {
        "key": "pricing", "label": "Pricing / Plans",
        "description": "Pricing tiers or packages with feature comparison",
        "enabled": True, "required": False, "category": "conversion",
        "fields": [
            {"key": "pricing_title", "label": "Section Title", "type": "text", "description": "Heading for pricing section", "min_length": 5, "max_length": 80},
            {"key": "pricing_subtitle", "label": "Section Subtitle", "type": "text", "description": "Brief value statement about pricing", "min_length": 10, "max_length": 200},
            {"key": "pricing_plans", "label": "Pricing Plans", "type": "card_list", "description": "2-4 pricing tiers", "min_items": 2, "max_items": 4,
             "card_fields": [{"key": "name", "label": "Plan Name", "type": "text"}, {"key": "price", "label": "Price", "type": "text"}, {"key": "period", "label": "Period", "type": "text"}, {"key": "description", "label": "Description", "type": "text"}, {"key": "features_list", "label": "Included Features", "type": "list"}, {"key": "cta_text", "label": "CTA Text", "type": "text"}, {"key": "highlighted", "label": "Highlighted/Popular", "type": "boolean"}]},
        ],
        "visual_options": {"layout": "columns|toggle-monthly-annual", "highlight_popular": True, "comparison_table": False},
        "ai_instructions": "Create realistic pricing tiers appropriate for the niche. Include a free/starter tier, a popular mid-tier (marked as recommended), and a premium tier. Each plan should have 4-6 specific features. Prices should be market-appropriate.",
        "order": 8,
    },
    {
        "key": "comparison", "label": "Comparison Table",
        "description": "Side-by-side comparison with competitors or plan features",
        "enabled": False, "required": False, "category": "conversion",
        "fields": [
            {"key": "comparison_title", "label": "Section Title", "type": "text", "description": "Heading for comparison section", "min_length": 5, "max_length": 80},
            {"key": "comparison_table", "label": "Comparison Data", "type": "table", "description": "Comparison table with headers and rows",
             "table_fields": {"headers": {"label": "Column Headers", "type": "list"}, "rows": {"label": "Data Rows", "type": "list_of_lists"}}},
            {"key": "comparison_points", "label": "Competitive Advantages", "type": "list", "description": "3-5 key differentiators", "min_items": 3, "max_items": 5},
        ],
        "visual_options": {"style": "table|cards|checklist", "highlight_winner": True},
        "ai_instructions": "Create a fair comparison that highlights advantages. Include real competitor categories (not named competitors). Use checkmarks and crosses. Be honest about trade-offs - credibility matters more than looking perfect.",
        "order": 9,
    },
    {
        "key": "gallery", "label": "Gallery / Portfolio",
        "description": "Visual showcase of work, products, or case studies",
        "enabled": False, "required": False, "category": "showcase",
        "fields": [
            {"key": "gallery_title", "label": "Section Title", "type": "text", "description": "Heading for gallery section", "min_length": 5, "max_length": 80},
            {"key": "gallery_sections", "label": "Gallery Items", "type": "card_list", "description": "4-8 gallery items with titles and descriptions", "min_items": 4, "max_items": 8,
             "card_fields": [{"key": "title", "label": "Title", "type": "text"}, {"key": "description", "label": "Description", "type": "textarea"}, {"key": "visual_concept", "label": "Visual Concept", "type": "text"}, {"key": "category", "label": "Category/Tag", "type": "text"}]},
        ],
        "visual_options": {"layout": "masonry|grid|carousel", "lightbox": True, "filter_tabs": True},
        "ai_instructions": "Create gallery items that showcase the best work or products. Each item needs a compelling title, descriptive text, and a visual concept description for image generation. Include category tags for filtering.",
        "order": 10,
    },
    {
        "key": "team", "label": "Team / About the People",
        "description": "Team member profiles with photos, roles, and bios",
        "enabled": False, "required": False, "category": "trust",
        "fields": [
            {"key": "team_title", "label": "Section Title", "type": "text", "description": "Heading for team section", "min_length": 5, "max_length": 80},
            {"key": "team_subtitle", "label": "Section Subtitle", "type": "text", "description": "Brief team introduction", "min_length": 10, "max_length": 200},
            {"key": "team_members", "label": "Team Members", "type": "card_list", "description": "3-6 team member profiles", "min_items": 2, "max_items": 6,
             "card_fields": [{"key": "name", "label": "Name", "type": "text"}, {"key": "role", "label": "Role/Title", "type": "text"}, {"key": "bio", "label": "Bio", "type": "textarea"}, {"key": "expertise", "label": "Expertise", "type": "text"}]},
        ],
        "visual_options": {"layout": "grid|cards-with-hover|list", "photos": True, "social_links": True},
        "ai_instructions": "Create realistic team profiles appropriate for this niche. Include diverse roles, relevant expertise, and authentic bios. Each person should feel real and credible for the industry.",
        "order": 11,
    },
    {
        "key": "faq", "label": "FAQ / Common Questions",
        "description": "Accordion-style frequently asked questions",
        "enabled": True, "required": True, "category": "trust",
        "fields": [
            {"key": "faq_items", "label": "FAQ Items", "type": "card_list", "description": "6-10 frequently asked questions with detailed answers", "min_items": 5, "max_items": 12,
             "card_fields": [{"key": "question", "label": "Question", "type": "text"}, {"key": "answer", "label": "Answer", "type": "textarea"}]},
        ],
        "visual_options": {"style": "accordion|expandable-cards|two-column", "animation": "slide-down|fade|none", "search": False},
        "ai_instructions": "Write 8 real questions a potential customer would ask. Include objection-handling questions (cost, time, trust). Answers should be 2-4 sentences, honest, and specific. Don't avoid hard questions.",
        "order": 12,
    },
    {
        "key": "resources", "label": "Resources / Blog Preview",
        "description": "Preview cards for blog posts, guides, or downloadable resources",
        "enabled": False, "required": False, "category": "content",
        "fields": [
            {"key": "resources_title", "label": "Section Title", "type": "text", "description": "Heading for resources section", "min_length": 5, "max_length": 80},
            {"key": "resources", "label": "Resource Cards", "type": "card_list", "description": "3-6 resource/article preview cards", "min_items": 3, "max_items": 6,
             "card_fields": [{"key": "title", "label": "Title", "type": "text"}, {"key": "description", "label": "Description", "type": "textarea"}, {"key": "category", "label": "Category", "type": "text"}, {"key": "read_time", "label": "Read Time", "type": "text"}]},
        ],
        "visual_options": {"layout": "grid|list|featured-plus-grid", "thumbnails": True},
        "ai_instructions": "Create resource preview cards for articles or guides relevant to the niche. Each should have a compelling title, 2-sentence description, category tag, and estimated read time. Content should demonstrate expertise.",
        "order": 13,
    },
    {
        "key": "contact", "label": "Contact / Get in Touch",
        "description": "Contact information, form, and location details",
        "enabled": True, "required": False, "category": "conversion",
        "fields": [
            {"key": "contact_title", "label": "Section Title", "type": "text", "description": "Heading for contact section", "min_length": 5, "max_length": 80},
            {"key": "contact_subtitle", "label": "Section Subtitle", "type": "text", "description": "Welcoming message encouraging contact", "min_length": 10, "max_length": 200},
            {"key": "contact_email", "label": "Email", "type": "text", "description": "Contact email address", "min_length": 0, "max_length": 100},
            {"key": "contact_methods", "label": "Contact Methods", "type": "card_list", "description": "2-4 ways to get in touch", "min_items": 2, "max_items": 4,
             "card_fields": [{"key": "method", "label": "Method", "type": "text"}, {"key": "value", "label": "Value/Link", "type": "text"}, {"key": "description", "label": "Description", "type": "text"}, {"key": "icon", "label": "Icon", "type": "icon_select"}]},
        ],
        "visual_options": {"form": True, "map": False, "style": "split|centered|card"},
        "ai_instructions": "Create a welcoming contact section. Include realistic contact methods appropriate for the niche (email, phone, social media, live chat). The messaging should reduce friction and encourage reaching out.",
        "order": 14,
    },
    {
        "key": "cta_final", "label": "Final CTA / Call to Action",
        "description": "Strong closing section with repeated value proposition and final call to action",
        "enabled": True, "required": True, "category": "conversion",
        "fields": [
            {"key": "cta_final_title", "label": "CTA Headline", "type": "text", "description": "Strong closing headline", "min_length": 10, "max_length": 100},
            {"key": "cta_final_body", "label": "CTA Body", "type": "textarea", "description": "1-2 sentences reinforcing the value and creating urgency", "min_length": 30, "max_length": 300},
            {"key": "cta_final_button", "label": "CTA Button Text", "type": "text", "description": "Final action button text", "min_length": 5, "max_length": 40},
        ],
        "visual_options": {"style": "gradient-bg|dark-bg|image-bg", "urgency_element": False},
        "ai_instructions": "Create a powerful closing CTA that summarizes the value and compels action. Use urgency without being pushy. Repeat the core benefit. This is the last chance to convert.",
        "order": 15,
    },
    {
        "key": "footer", "label": "Footer",
        "description": "Site footer with brand, links, legal, and social media",
        "enabled": True, "required": True, "category": "core",
        "fields": [
            {"key": "footer_tagline", "label": "Footer Tagline", "type": "text", "description": "Short brand tagline for the footer", "min_length": 0, "max_length": 100},
            {"key": "footer_links", "label": "Footer Links", "type": "card_list", "description": "Navigation link groups", "min_items": 0, "max_items": 4,
             "card_fields": [{"key": "group_title", "label": "Group Title", "type": "text"}, {"key": "links", "label": "Links", "type": "list"}]},
        ],
        "visual_options": {"style": "minimal|multi-column|mega-footer", "social_links": True, "newsletter_signup": False},
        "ai_instructions": "Create footer content with organized link groups and social media presence. Include appropriate legal links (Privacy, Terms). Keep it professional and complete.",
        "order": 16,
    },
]

LEGENDARY_SECTION_OVERRIDES = {
    "hero": "Create a hero section that would make a Fortune 500 CMO pause. The headline must be unexpected yet immediately clear - use a power structure like [Specific Outcome] + [Without Common Sacrifice] or [Provocative Question That Reframes the Problem]. Subheadline must add a concrete proof point or statistic. Hero body must follow a 5-sentence narrative arc: (1) Name the pain vividly, (2) Explain why current solutions fail, (3) Introduce the insight/approach, (4) Provide a specific proof point, (5) Make the next step feel inevitable. CTA must be benefit-driven ('Start Saving 40% Today' not 'Get Started'). Secondary CTA should reduce commitment anxiety ('See How It Works' or 'View Case Studies').",
    "problem": "Write a problem section that makes the reader say 'they get me.' Name 3-5 SPECIFIC daily scenarios the audience faces - not abstract concepts. Use sensory language: what does this problem FEEL like at 11pm on a Tuesday? Include at least one data point about the cost of inaction. Pain points must be concrete ('Spending 14 hours/week on manual data entry') not vague ('Inefficient processes'). End with an implicit question: 'What if there was a better way?'",
    "solution": "Present the solution as a revelation, not a sales pitch. Start with the core insight - the non-obvious truth that makes this approach work. Explain the MECHANISM: not just 'we solve X' but 'here's specifically how.' Each benefit must be paired with a concrete outcome: 'Automated intake forms → 73% fewer data entry errors in week one.' Include a 'before/after' narrative that makes the transformation tangible. Address the skeptic: briefly acknowledge why other solutions fail and what's fundamentally different here.",
    "about": "Tell a founder story with genuine emotional stakes. Include: (1) A specific moment of frustration that sparked the idea - date, place, what happened, (2) The insight that changed everything, (3) Early struggles and what was learned, (4) The team's genuine expertise (years of experience, specific credentials, past wins), (5) A mission statement that's actually specific ('We exist to eliminate the 23 hours/month small business owners waste on compliance paperwork' not 'We're passionate about helping businesses succeed'). Write minimum 8 sentences with narrative tension.",
    "features": "Generate 6-9 feature cards that read like mini case studies. Each feature: (1) A title that names the OUTCOME not the feature ('Cut Report Time from 4 Hours to 12 Minutes' not 'Automated Reporting'), (2) A 3-sentence description following [What it does specifically] → [How it works differently than competitors] → [Measurable result users get]. No two features should use the same sentence structure. Avoid ALL generic descriptors - every adjective must be replaceable with a number or specific example.",
    "how_it_works": "Create a step-by-step process that makes complexity feel simple. Each step: specific title (verb-first), 2-3 sentence description with a concrete example, and a subtle emotional payoff (what the user FEELS at this step). Include realistic timeframes ('Step 1 takes about 5 minutes'). The progression should build confidence - each step should feel easier than the last. Final step should connect to the outcome promised in the hero.",
    "stats": "Generate 4-6 statistics that pass the 'CEO presentation' test. Each stat must: (1) Use a specific, non-round number (not '100+' or '99%' - instead '2,847' or '94.3%'), (2) Include comparison context ('3.2x faster than the industry average' or 'vs. 23% for traditional methods'), (3) Be plausible for the niche and business stage. Include a mix: one about speed/time saved, one about money saved/earned, one about customer satisfaction, one about scale/reach. Context descriptions should explain WHY this number matters.",
    "testimonials": "Write 4-6 testimonials that sound like real humans, not marketing copy. Requirements: (1) Each must include a specific metric or timeframe ('reduced our onboarding time from 3 weeks to 4 days'), (2) At least one should mention a minor initial concern that was overcome ('I was skeptical about switching from [competitor], but...'), (3) Use natural speech patterns - contractions, run-on thoughts, enthusiasm that feels earned not scripted, (4) Diverse perspectives: different company sizes, roles, and use cases, (5) Names must feel real and culturally diverse, with specific, plausible job titles and company descriptions. NEVER write 'This product changed my life!' - that's marketing, not a testimonial.",
    "pricing": "Create pricing tiers that feel researched and strategically positioned. Requirements: (1) Each tier name should communicate value ('Growth' not 'Pro'), (2) Prices must be market-appropriate for the niche - research what competitors charge, (3) Feature lists should use outcome language ('Unlimited team collaboration' not 'Multi-user access'), (4) The recommended tier should feel like obvious best value (not just 'most popular'), (5) Include a clear upgrade path logic - each tier should solve a bigger problem. Add a subtle psychological anchor: the premium tier should make the mid-tier feel reasonable.",
    "comparison": "Build a comparison that wins trust through honesty. Requirements: (1) Compare against real competitor CATEGORIES (not named competitors), (2) Be honest - show 1-2 areas where alternatives might be adequate, but frame your differentiators as decisive, (3) Use specific criteria that matter to buyers (not just feature checkboxes), (4) Include a 'Bottom Line' row that summarizes the value difference, (5) Competitive advantages should reference specific, measurable differences.",
    "gallery": "Create gallery items that tell a visual story of capability. Each item: a compelling title, a 2-3 sentence description that implies the skill/quality behind the work, a specific visual concept for image generation, and a category tag. Items should showcase RANGE: different project types, scales, and industries if applicable. Visual concepts should be specific enough to generate impressive images.",
    "team": "Create team profiles that build genuine credibility. Each member: a believable name, a specific title, a 3-sentence bio that includes (1) relevant credential or years of experience, (2) a specific past achievement or specialization, (3) a personal detail that makes them human. Include diverse backgrounds and complementary expertise. Roles should make strategic sense for the business stage.",
    "faq": "Write 8-10 FAQs that actually address what real buyers worry about. MUST include: (1) A price objection question with honest answer about ROI, (2) A 'vs free alternatives' question that acknowledges free options exist but explains the difference, (3) A trust/security question with specific answer, (4) A 'is this right for me?' question with an honest 'this might NOT be for you if...' component, (5) Technical questions relevant to the niche. Answers: 3-5 sentences, specific, honest, never evasive. Show confidence by addressing hard questions head-on.",
    "resources": "Create resource previews that demonstrate deep expertise. Each resource: compelling title (use proven content formulas: 'How [Company] Achieved [Specific Result] in [Timeframe]'), 2-3 sentence description that creates genuine curiosity, specific category, and realistic read time. Resources should cover the customer journey: awareness → consideration → decision. Include a mix of formats: guides, case studies, comparisons, how-tos.",
    "contact": "Create a contact section that reduces friction to zero. Welcoming headline that promises something ('Get Your Custom Growth Plan' not 'Contact Us'). Subtitle should set expectations ('Response within 4 business hours'). Include 3-4 contact methods appropriate for the business type, each with a specific description of what to expect. The overall tone should make reaching out feel like a valuable next step, not a sales trap.",
    "cta_final": "Create a closing CTA that feels like the inevitable conclusion to everything above. Headline should restate the core transformation in fresh language. Body should create gentle urgency with specificity ('The average new client saves 12 hours in their first week - your clock starts when you do'). Button text should be the most compelling action phrase on the entire page. This section should make NOT clicking feel like a loss.",
    "footer": "Create footer content that signals professionalism and completeness. Include organized link groups (Product, Company, Resources, Legal). Footer tagline should be a condensed version of the value proposition. Link structure should signal a mature, well-organized company - not a landing page.",
}

CONTENT_DEPTH_PRESETS = {
    "minimal": {
        "label": "Minimal",
        "description": "Quick landing page - 5 sections, concise copy",
        "sections": ["hero", "features", "testimonials", "faq", "cta_final", "footer"],
        "content_multiplier": 0.7,
    },
    "standard": {
        "label": "Standard",
        "description": "Professional business site - 9 sections, balanced copy",
        "sections": ["hero", "problem", "solution", "about", "features", "stats", "testimonials", "faq", "cta_final", "footer"],
        "content_multiplier": 1.0,
    },
    "comprehensive": {
        "label": "Comprehensive",
        "description": "Complete business-in-a-box - 13 sections, detailed copy",
        "sections": ["hero", "problem", "solution", "about", "features", "how_it_works", "stats", "testimonials", "pricing", "faq", "contact", "cta_final", "footer"],
        "content_multiplier": 1.3,
    },
    "legendary": {
        "label": "LEGENDARY",
        "description": "Enterprise-grade output - all 16 sections with elite AI instructions, banned cliches, concrete specificity, $50K agency quality.",
        "sections": [s["key"] for s in _RAW_SECTIONS],
        "content_multiplier": 1.8,
    },
}

DEFAULT_SECTION_KEYS = [s["key"] for s in _RAW_SECTIONS]


def _raw_to_section_def(raw: dict) -> SectionDefinition:
    fields = []
    for f in raw.get("fields", []):
        fields.append(FieldDefinition(
            key=f["key"],
            label=f["label"],
            type=f["type"],
            description=f.get("description", ""),
            min_length=f.get("min_length", 0),
            max_length=f.get("max_length", 0),
            min_items=f.get("min_items", 0),
            max_items=f.get("max_items", 0),
            card_fields=f.get("card_fields", []),
            table_fields=f.get("table_fields"),
        ))
    return SectionDefinition(
        key=raw["key"],
        label=raw["label"],
        description=raw["description"],
        enabled=raw.get("enabled", True),
        required=raw.get("required", False),
        category=raw.get("category", "core"),
        fields=fields,
        visual_options=raw.get("visual_options", {}),
        ai_instructions=raw.get("ai_instructions", ""),
        order=raw.get("order", 0),
    )


def get_section_definitions() -> list[SectionDefinition]:
    return [_raw_to_section_def(r) for r in _RAW_SECTIONS]


def get_section_by_key(key: str) -> Optional[SectionDefinition]:
    for r in _RAW_SECTIONS:
        if r["key"] == key:
            return _raw_to_section_def(r)
    return None


def get_depth_presets() -> dict:
    return copy.deepcopy(CONTENT_DEPTH_PRESETS)


def get_default_blueprint(depth: str = "comprehensive") -> BlueprintConfig:
    preset = CONTENT_DEPTH_PRESETS.get(depth, CONTENT_DEPTH_PRESETS["comprehensive"])
    if depth not in CONTENT_DEPTH_PRESETS:
        depth = "comprehensive"
    sections = get_section_definitions()
    for section in sections:
        section.enabled = section.key in preset["sections"]
    return BlueprintConfig(
        depth=depth,
        depth_label=preset["label"],
        content_multiplier=preset["content_multiplier"],
        sections=sections,
        global_settings={
            "tone": "professional",
            "formality": "business-casual",
            "target_word_count": "high",
            "include_cta_in_every_section": True,
            "seo_optimized": True,
        },
        visual_settings={
            "animation_level": "subtle",
            "card_style": "elevated",
            "layout_pattern": "sectioned",
            "color_scheme": "brand",
            "dark_mode_support": False,
            "mobile_first": True,
            "tailwind_version": "3.x-cdn",
        },
    )


def validate_blueprint(bp: BlueprintConfig) -> BlueprintValidation:
    errors = []
    if not bp.sections:
        errors.append("Blueprint must have at least one section")
    enabled = [s for s in bp.sections if s.enabled]
    if not enabled:
        errors.append("At least one section must be enabled")
    required_keys = {"hero", "footer"}
    enabled_keys = {s.key for s in enabled}
    missing = required_keys - enabled_keys
    if missing:
        errors.append(f"Required sections missing: {', '.join(sorted(missing))}")
    return BlueprintValidation(valid=len(errors) == 0, errors=errors)


def blueprint_to_prompt_spec(bp: BlueprintConfig) -> tuple[str, str]:
    enabled = sorted(
        [s for s in bp.sections if s.enabled],
        key=lambda s: s.order,
    )
    multiplier = bp.content_multiplier
    is_legendary = bp.depth == "legendary"

    spec_parts = []
    json_schema_parts = []

    for section in enabled:
        key = section.key
        label = section.label
        ai_inst = section.ai_instructions
        if is_legendary and key in LEGENDARY_SECTION_OVERRIDES:
            ai_inst = LEGENDARY_SECTION_OVERRIDES[key]

        spec_parts.append(f"\n### {label} (key: \"{key}\")")
        spec_parts.append(f"Instructions: {ai_inst}")

        field_specs = []
        for field in section.fields:
            fkey = field.key
            ftype = field.type
            fdesc = field.description

            if ftype == "text":
                min_l = int(field.min_length * multiplier)
                max_l = int(field.max_length * multiplier)
                field_specs.append(f'    "{fkey}": "string ({min_l}-{max_l} chars) - {fdesc}"')
            elif ftype == "textarea":
                min_l = int(field.min_length * multiplier)
                max_l = int(field.max_length * multiplier)
                field_specs.append(f'    "{fkey}": "string ({min_l}-{max_l} chars) - {fdesc}"')
            elif ftype == "list":
                min_i = field.min_items
                max_i = int(field.max_items * multiplier)
                field_specs.append(f'    "{fkey}": ["item1", "item2", ...] ({min_i}-{max_i} items) - {fdesc}')
            elif ftype == "card_list":
                min_i = field.min_items
                max_i = int(field.max_items * multiplier)
                cf_keys = ", ".join([f'"{cf["key"]}"' for cf in field.card_fields])
                field_specs.append(f'    "{fkey}": [{{ {cf_keys} }}, ...] ({min_i}-{max_i} items) - {fdesc}')
            elif ftype == "table":
                field_specs.append(f'    "{fkey}": {{"headers": [...], "rows": [[...], ...]}} - {fdesc}')
            elif ftype == "boolean":
                field_specs.append(f'    "{fkey}": true/false - {fdesc}')

        json_schema_parts.append(f'  "{key}": {{\n' + ",\n".join(field_specs) + "\n  }")

    prompt_spec = "\n".join(spec_parts)
    json_schema = '{\n  "site_copy": {\n' + ",\n".join(json_schema_parts) + "\n  }\n}"
    return prompt_spec, json_schema


def calculate_completeness(site_copy: Optional[dict], bp: Optional[BlueprintConfig]) -> dict:
    if not site_copy or not bp:
        return {"score": 0, "total": 0, "filled": 0, "sections": {}}

    enabled = [s for s in bp.sections if s.enabled]
    total_fields = 0
    filled_fields = 0
    section_scores = {}

    for section in enabled:
        key = section.key
        section_data = site_copy.get(key, {})
        if not isinstance(section_data, dict):
            if key in site_copy and site_copy[key]:
                section_data = {key: site_copy[key]}
            else:
                section_data = {}

        s_total = 0
        s_filled = 0
        for field in section.fields:
            fkey = field.key
            s_total += 1
            total_fields += 1
            val = site_copy.get(fkey) or section_data.get(fkey)
            if val:
                if isinstance(val, str) and len(val.strip()) > 0:
                    s_filled += 1
                    filled_fields += 1
                elif isinstance(val, list) and len(val) > 0:
                    s_filled += 1
                    filled_fields += 1
                elif isinstance(val, dict) and len(val) > 0:
                    s_filled += 1
                    filled_fields += 1

        section_scores[key] = {
            "label": section.label,
            "total": s_total,
            "filled": s_filled,
            "score": round((s_filled / s_total * 100) if s_total > 0 else 0),
        }

    overall = round((filled_fields / total_fields * 100) if total_fields > 0 else 0)
    return {
        "score": overall,
        "total": total_fields,
        "filled": filled_fields,
        "sections": section_scores,
    }


@aura_module(
    name="blueprint",
    version="1.0.0",
    description="Site blueprint engine — 16 section types, 4 depth presets, validation, prompt spec generation, completeness scoring",
    input_model=BlueprintInput,
)
def generate_blueprint(config: dict) -> ModuleResult:
    depth = config.get("depth", "comprehensive")
    bp = get_default_blueprint(depth)
    validation = validate_blueprint(bp)
    prompt_spec, json_schema = blueprint_to_prompt_spec(bp)

    return ModuleResult(
        ok=validation.valid,
        output={
            "blueprint": bp.model_dump(),
            "validation": validation.model_dump(),
            "prompt_spec": prompt_spec,
            "json_schema": json_schema,
        },
    )
