import copy
import json
import re
from app.services.blueprint import DEFAULT_SECTIONS, CONTENT_DEPTH_PRESETS

DISCOVERY_FIELDS_DEFAULT = [
    {
        "step": 1,
        "step_title": "Vision & Goals",
        "step_description": "Tell us the big picture. What's the story behind this project?",
        "fields": [
            {"key": "project_story", "label": "What's the big-picture goal for this website?", "type": "textarea", "placeholder": "e.g., I want to create a trusted resource for first-time homebuyers that generates passive income through affiliate partnerships..."},
            {"key": "success_vision", "label": "What does success look like in 1-5 years?", "type": "textarea", "placeholder": "e.g., 50K monthly visitors, $5K/mo in affiliate revenue, recognized brand in the space..."},
            {"key": "one_thing", "label": "If this site could do ONE thing perfectly, what would it be?", "type": "input", "placeholder": "e.g., Help people compare options and make confident decisions"},
        ],
    },
    {
        "step": 2,
        "step_title": "Target Audience",
        "step_description": "Describe the most important person this website is for.",
        "fields": [
            {"key": "ideal_audience", "label": "Who is your ideal visitor? What are their challenges?", "type": "textarea", "placeholder": "e.g., Busy professionals aged 30-50 who want to invest but feel overwhelmed by options..."},
            {"key": "audience_journey", "label": "How do they find you? What's their journey?", "type": "textarea", "placeholder": "e.g., They Google questions, read comparison articles, look for trusted recommendations..."},
            {"key": "primary_action", "label": "What's the primary action visitors should take?", "type": "input", "placeholder": "e.g., Sign up for newsletter, click affiliate link, book consultation"},
        ],
    },
    {
        "step": 3,
        "step_title": "Brand & Style",
        "step_description": "Define the personality and visual feel of your brand.",
        "fields": [
            {"key": "brand_personality", "label": "If your brand were a person, how would you describe them?", "type": "textarea", "placeholder": "e.g., A knowledgeable friend who explains complex things simply, warm but professional..."},
            {"key": "color_palette", "label": "Color Palette Feel", "type": "select", "options": ["", "Warm & Inviting", "Cool & Professional", "Earthy & Natural", "Bold & Vibrant", "Monochromatic & Minimalist", "Dark & Moody"]},
            {"key": "visual_style", "label": "Visual Style", "type": "select", "options": ["", "Minimalist & Clean", "Corporate & Professional", "Playful & Creative", "Elegant & Luxurious", "Tech & Futuristic", "Rustic & Handmade"]},
            {"key": "core_values", "label": "Core values & differentiator", "type": "input", "placeholder": "e.g., Transparency, simplicity, trust"},
            {"key": "desired_feeling", "label": "How should visitors FEEL when they land on the site?", "type": "input", "placeholder": "e.g., Confident, relieved, inspired, informed"},
        ],
    },
    {
        "step": 4,
        "step_title": "Features & Future",
        "step_description": "What should the site do, and where should it go?",
        "fields": [
            {"key": "key_features", "label": "Key features or sections needed?", "type": "textarea", "placeholder": "e.g., Blog, comparison tables, newsletter signup, resource library, booking calendar..."},
            {"key": "sites_loved", "label": "Websites you love (and why)?", "type": "textarea", "placeholder": "e.g., NerdWallet - clean comparisons; Wirecutter - trustworthy reviews..."},
            {"key": "future_vision", "label": "Future vision: How will this site evolve?", "type": "textarea", "placeholder": "e.g., Add premium membership, online courses, expand into adjacent niches..."},
            {"key": "additional_notes", "label": "Anything else we should know?", "type": "input", "placeholder": "Any other preferences, must-haves, or things to avoid"},
        ],
    },
]


def build_default_profile_config():
    section_keys = [s["key"] for s in DEFAULT_SECTIONS]
    enabled_by_default = [s["key"] for s in DEFAULT_SECTIONS if s.get("enabled")]
    return {
        "sections": section_keys,
        "enabled_sections": enabled_by_default,
        "depth_presets": copy.deepcopy(CONTENT_DEPTH_PRESETS),
        "discovery_fields": copy.deepcopy(DISCOVERY_FIELDS_DEFAULT),
        "prompt_overrides": {},
        "visual_defaults": {
            "color_scheme": "brand",
            "card_style": "elevated",
            "animation": "fade-in",
            "layout": "single-scroll",
        },
        "meta": {
            "version": "1.0",
            "compatible_depths": ["minimal", "standard", "comprehensive", "legendary"],
        },
    }


STARTER_PROFILES = [
    {
        "name": "Affiliate Landing Page",
        "slug": "affiliate-landing",
        "description": "High-conversion single-page site optimized for affiliate revenue. Comparison tables, trust signals, and strong CTAs. Minimal friction, maximum click-through.",
        "config": {
            "sections": ["hero", "problem", "solution", "features", "comparison", "stats", "testimonials", "faq", "cta_final", "footer"],
            "enabled_sections": ["hero", "problem", "solution", "features", "comparison", "stats", "testimonials", "faq", "cta_final", "footer"],
            "depth_presets": {
                "minimal": {"label": "Quick Lander", "sections": ["hero", "features", "testimonials", "cta_final", "footer"], "content_multiplier": 0.7},
                "standard": {"label": "Full Funnel", "sections": ["hero", "problem", "solution", "features", "comparison", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.0},
                "comprehensive": {"label": "Authority Affiliate", "sections": ["hero", "problem", "solution", "features", "comparison", "stats", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.3},
                "legendary": {"label": "LEGENDARY", "sections": ["hero", "problem", "solution", "features", "comparison", "stats", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.8},
            },
            "discovery_fields": [
                {
                    "step": 1, "step_title": "Affiliate Strategy", "step_description": "Define your monetization approach.",
                    "fields": [
                        {"key": "project_story", "label": "What products/services will you promote?", "type": "textarea", "placeholder": "e.g., Web hosting services, VPN providers, financial tools..."},
                        {"key": "success_vision", "label": "Revenue goal and timeline?", "type": "textarea", "placeholder": "e.g., $3K/mo passive income within 12 months..."},
                        {"key": "one_thing", "label": "What's your unique angle vs other affiliate sites?", "type": "input", "placeholder": "e.g., Hands-on testing of every product, not just regurgitated specs"},
                    ],
                },
                {
                    "step": 2, "step_title": "Buyer Profile", "step_description": "Who's clicking your affiliate links?",
                    "fields": [
                        {"key": "ideal_audience", "label": "Describe the person ready to buy", "type": "textarea", "placeholder": "e.g., Small business owners comparing SaaS tools, ready to purchase but need guidance..."},
                        {"key": "audience_journey", "label": "What triggers their search?", "type": "textarea", "placeholder": "e.g., They just got frustrated with their current tool, or a friend recommended switching..."},
                        {"key": "primary_action", "label": "Primary conversion action", "type": "input", "placeholder": "e.g., Click comparison table affiliate link, use discount code"},
                    ],
                },
                {
                    "step": 3, "step_title": "Brand & Trust", "step_description": "Affiliate sites live and die by trust.",
                    "fields": [
                        {"key": "brand_personality", "label": "What voice builds trust in this niche?", "type": "textarea", "placeholder": "e.g., Honest reviewer who calls out cons too, data-driven, no hype..."},
                        {"key": "color_palette", "label": "Color Palette Feel", "type": "select", "options": ["", "Warm & Inviting", "Cool & Professional", "Earthy & Natural", "Bold & Vibrant", "Monochromatic & Minimalist", "Dark & Moody"]},
                        {"key": "visual_style", "label": "Visual Style", "type": "select", "options": ["", "Minimalist & Clean", "Corporate & Professional", "Playful & Creative", "Elegant & Luxurious", "Tech & Futuristic", "Rustic & Handmade"]},
                        {"key": "core_values", "label": "Trust signals that matter most", "type": "input", "placeholder": "e.g., Verified purchases, transparent methodology, no sponsored rankings"},
                        {"key": "desired_feeling", "label": "How should visitors feel?", "type": "input", "placeholder": "e.g., Confident they're getting unbiased advice"},
                    ],
                },
                {
                    "step": 4, "step_title": "Competitor & Content", "step_description": "Know the landscape.",
                    "fields": [
                        {"key": "key_features", "label": "Must-have page elements?", "type": "textarea", "placeholder": "e.g., Comparison tables, pros/cons lists, star ratings, discount badges..."},
                        {"key": "sites_loved", "label": "Affiliate sites you admire?", "type": "textarea", "placeholder": "e.g., Wirecutter - editorial quality; NerdWallet - data presentation..."},
                        {"key": "future_vision", "label": "Growth path?", "type": "textarea", "placeholder": "e.g., Expand to adjacent product categories, add email list, create buying guides..."},
                        {"key": "additional_notes", "label": "Anything else?", "type": "input", "placeholder": "Specific affiliate programs, FTC compliance notes, etc."},
                    ],
                },
            ],
            "prompt_overrides": {
                "global_tone": "Write as an authoritative, honest reviewer. Always mention pros AND cons. Use comparison language. Optimize for buyer-intent keywords.",
            },
            "visual_defaults": {"color_scheme": "complementary", "card_style": "bordered", "animation": "fade-in", "layout": "single-scroll"},
            "meta": {"version": "1.0", "compatible_depths": ["minimal", "standard", "comprehensive", "legendary"]},
        },
    },
    {
        "name": "Authority Knowledge Base",
        "slug": "authority-knowledge",
        "description": "Content-rich authority site with resource library, team profiles, and educational sections. Designed for thought leadership and organic traffic.",
        "config": {
            "sections": ["hero", "about", "features", "how_it_works", "stats", "team", "resources", "testimonials", "faq", "contact", "cta_final", "footer"],
            "enabled_sections": ["hero", "about", "features", "how_it_works", "stats", "team", "resources", "testimonials", "faq", "contact", "cta_final", "footer"],
            "depth_presets": {
                "minimal": {"label": "Quick Authority", "sections": ["hero", "about", "features", "faq", "footer"], "content_multiplier": 0.7},
                "standard": {"label": "Knowledge Hub", "sections": ["hero", "about", "features", "how_it_works", "resources", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.0},
                "comprehensive": {"label": "Full Authority", "sections": ["hero", "about", "features", "how_it_works", "stats", "team", "resources", "testimonials", "faq", "contact", "cta_final", "footer"], "content_multiplier": 1.3},
                "legendary": {"label": "LEGENDARY", "sections": ["hero", "about", "features", "how_it_works", "stats", "team", "resources", "testimonials", "faq", "contact", "cta_final", "footer"], "content_multiplier": 1.8},
            },
            "discovery_fields": [
                {
                    "step": 1, "step_title": "Expertise & Mission", "step_description": "What knowledge are you sharing with the world?",
                    "fields": [
                        {"key": "project_story", "label": "What's your area of expertise?", "type": "textarea", "placeholder": "e.g., 15 years in cybersecurity, specializing in small business protection..."},
                        {"key": "success_vision", "label": "What impact do you want to have?", "type": "textarea", "placeholder": "e.g., Become the go-to resource for SMB security, 100K monthly readers..."},
                        {"key": "one_thing", "label": "Your unique insight that nobody else teaches?", "type": "input", "placeholder": "e.g., Practical security that doesn't require a PhD or enterprise budget"},
                    ],
                },
                {
                    "step": 2, "step_title": "Audience & Learning", "step_description": "Who are your students/readers?",
                    "fields": [
                        {"key": "ideal_audience", "label": "Who needs your knowledge most?", "type": "textarea", "placeholder": "e.g., Non-technical business owners who know they're vulnerable but don't know where to start..."},
                        {"key": "audience_journey", "label": "How do they currently learn about this topic?", "type": "textarea", "placeholder": "e.g., YouTube tutorials, Reddit threads, vendor marketing (often biased)..."},
                        {"key": "primary_action", "label": "What should they do first?", "type": "input", "placeholder": "e.g., Download the free security checklist, subscribe to weekly briefings"},
                    ],
                },
                {
                    "step": 3, "step_title": "Brand & Voice", "step_description": "Define your teaching personality.",
                    "fields": [
                        {"key": "brand_personality", "label": "Your teaching style?", "type": "textarea", "placeholder": "e.g., Patient mentor who uses real-world analogies, never talks down..."},
                        {"key": "color_palette", "label": "Color Palette Feel", "type": "select", "options": ["", "Warm & Inviting", "Cool & Professional", "Earthy & Natural", "Bold & Vibrant", "Monochromatic & Minimalist", "Dark & Moody"]},
                        {"key": "visual_style", "label": "Visual Style", "type": "select", "options": ["", "Minimalist & Clean", "Corporate & Professional", "Playful & Creative", "Elegant & Luxurious", "Tech & Futuristic", "Rustic & Handmade"]},
                        {"key": "core_values", "label": "Core principles of your content?", "type": "input", "placeholder": "e.g., Accuracy, accessibility, actionable advice"},
                        {"key": "desired_feeling", "label": "How should readers feel?", "type": "input", "placeholder": "e.g., Empowered, informed, capable of taking action"},
                    ],
                },
                {
                    "step": 4, "step_title": "Content Strategy", "step_description": "Plan your knowledge library.",
                    "fields": [
                        {"key": "key_features", "label": "Content types you'll create?", "type": "textarea", "placeholder": "e.g., How-to guides, case studies, tool reviews, weekly newsletter, video tutorials..."},
                        {"key": "sites_loved", "label": "Knowledge sites you admire?", "type": "textarea", "placeholder": "e.g., Moz - SEO guides; Krebs on Security - investigative depth..."},
                        {"key": "future_vision", "label": "Content expansion plans?", "type": "textarea", "placeholder": "e.g., Online courses, certification program, community forum, podcast..."},
                        {"key": "additional_notes", "label": "Anything else?", "type": "input", "placeholder": "Credentials, partnerships, content calendar ideas"},
                    ],
                },
            ],
            "prompt_overrides": {
                "global_tone": "Write as a respected educator and thought leader. Demonstrate deep expertise. Use clear explanations with examples. Prioritize accuracy and actionability over marketing hype.",
            },
            "visual_defaults": {"color_scheme": "brand", "card_style": "elevated", "animation": "scroll-reveal", "layout": "magazine"},
            "meta": {"version": "1.0", "compatible_depths": ["minimal", "standard", "comprehensive", "legendary"]},
        },
    },
    {
        "name": "SaaS Product Page",
        "slug": "saas-product",
        "description": "Software product landing page with feature highlights, pricing tiers, how-it-works demos, and conversion-optimized layout. Built for signups and trials.",
        "config": {
            "sections": ["hero", "problem", "solution", "features", "how_it_works", "stats", "pricing", "comparison", "testimonials", "faq", "cta_final", "footer"],
            "enabled_sections": ["hero", "problem", "solution", "features", "how_it_works", "stats", "pricing", "comparison", "testimonials", "faq", "cta_final", "footer"],
            "depth_presets": {
                "minimal": {"label": "Launch Page", "sections": ["hero", "features", "pricing", "cta_final", "footer"], "content_multiplier": 0.7},
                "standard": {"label": "Product Page", "sections": ["hero", "problem", "solution", "features", "how_it_works", "pricing", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.0},
                "comprehensive": {"label": "Full Product Site", "sections": ["hero", "problem", "solution", "features", "how_it_works", "stats", "pricing", "comparison", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.3},
                "legendary": {"label": "LEGENDARY", "sections": ["hero", "problem", "solution", "features", "how_it_works", "stats", "pricing", "comparison", "testimonials", "faq", "cta_final", "footer"], "content_multiplier": 1.8},
            },
            "discovery_fields": [
                {
                    "step": 1, "step_title": "Product & Vision", "step_description": "What does your software do?",
                    "fields": [
                        {"key": "project_story", "label": "Describe your product in one paragraph", "type": "textarea", "placeholder": "e.g., A project management tool that combines task tracking with AI-powered time estimates..."},
                        {"key": "success_vision", "label": "Growth targets?", "type": "textarea", "placeholder": "e.g., 1000 paying users in 6 months, $50K MRR by end of year..."},
                        {"key": "one_thing", "label": "Your #1 feature that competitors lack?", "type": "input", "placeholder": "e.g., AI that learns your team's velocity and auto-adjusts deadlines"},
                    ],
                },
                {
                    "step": 2, "step_title": "Users & Workflow", "step_description": "Who uses your software and how?",
                    "fields": [
                        {"key": "ideal_audience", "label": "Primary user persona?", "type": "textarea", "placeholder": "e.g., Engineering managers at 20-100 person startups juggling multiple projects..."},
                        {"key": "audience_journey", "label": "How do they discover tools like yours?", "type": "textarea", "placeholder": "e.g., G2 reviews, ProductHunt, colleague recommendations, Google searches..."},
                        {"key": "primary_action", "label": "Primary conversion goal?", "type": "input", "placeholder": "e.g., Start free trial, book a demo, sign up for freemium plan"},
                    ],
                },
                {
                    "step": 3, "step_title": "Brand & Design", "step_description": "Your product's visual identity.",
                    "fields": [
                        {"key": "brand_personality", "label": "Product personality?", "type": "textarea", "placeholder": "e.g., Smart and capable but never complicated, like having a senior PM on the team..."},
                        {"key": "color_palette", "label": "Color Palette Feel", "type": "select", "options": ["", "Warm & Inviting", "Cool & Professional", "Earthy & Natural", "Bold & Vibrant", "Monochromatic & Minimalist", "Dark & Moody"]},
                        {"key": "visual_style", "label": "Visual Style", "type": "select", "options": ["", "Minimalist & Clean", "Corporate & Professional", "Playful & Creative", "Elegant & Luxurious", "Tech & Futuristic", "Rustic & Handmade"]},
                        {"key": "core_values", "label": "Product values?", "type": "input", "placeholder": "e.g., Simplicity, reliability, speed"},
                        {"key": "desired_feeling", "label": "First impression goal?", "type": "input", "placeholder": "e.g., This is the tool I've been looking for"},
                    ],
                },
                {
                    "step": 4, "step_title": "Pricing & Competition", "step_description": "Market positioning.",
                    "fields": [
                        {"key": "key_features", "label": "Top 5 features to highlight?", "type": "textarea", "placeholder": "e.g., Real-time collaboration, AI estimates, Gantt charts, integrations, mobile app..."},
                        {"key": "sites_loved", "label": "Competitor sites with great design?", "type": "textarea", "placeholder": "e.g., Linear - clean minimal; Notion - friendly onboarding; Slack - fun personality..."},
                        {"key": "future_vision", "label": "Product roadmap highlights?", "type": "textarea", "placeholder": "e.g., Enterprise tier, API marketplace, white-label option..."},
                        {"key": "additional_notes", "label": "Pricing model notes?", "type": "input", "placeholder": "e.g., Freemium + Pro ($19/mo) + Enterprise (custom), annual discount"},
                    ],
                },
            ],
            "prompt_overrides": {
                "global_tone": "Write as a modern SaaS company. Be clear, benefit-focused, and conversion-optimized. Show don't tell - reference specific features and outcomes. Use social proof from recognizable company types.",
            },
            "visual_defaults": {"color_scheme": "brand", "card_style": "glass", "animation": "stagger-fade", "layout": "sectioned"},
            "meta": {"version": "1.0", "compatible_depths": ["minimal", "standard", "comprehensive", "legendary"]},
        },
    },
    {
        "name": "Local Services Business",
        "slug": "local-services",
        "description": "Service-area business site with contact-heavy layout, team profiles, gallery of work, and trust-building sections. Optimized for phone calls and form submissions.",
        "config": {
            "sections": ["hero", "about", "features", "how_it_works", "gallery", "stats", "team", "testimonials", "faq", "contact", "cta_final", "footer"],
            "enabled_sections": ["hero", "about", "features", "how_it_works", "gallery", "stats", "team", "testimonials", "faq", "contact", "cta_final", "footer"],
            "depth_presets": {
                "minimal": {"label": "Quick Presence", "sections": ["hero", "about", "features", "contact", "footer"], "content_multiplier": 0.7},
                "standard": {"label": "Service Page", "sections": ["hero", "about", "features", "how_it_works", "testimonials", "faq", "contact", "cta_final", "footer"], "content_multiplier": 1.0},
                "comprehensive": {"label": "Full Business Site", "sections": ["hero", "about", "features", "how_it_works", "gallery", "stats", "team", "testimonials", "faq", "contact", "cta_final", "footer"], "content_multiplier": 1.3},
                "legendary": {"label": "LEGENDARY", "sections": ["hero", "about", "features", "how_it_works", "gallery", "stats", "team", "testimonials", "faq", "contact", "cta_final", "footer"], "content_multiplier": 1.8},
            },
            "discovery_fields": [
                {
                    "step": 1, "step_title": "Business & Services", "step_description": "What do you do and where?",
                    "fields": [
                        {"key": "project_story", "label": "Describe your business and service area", "type": "textarea", "placeholder": "e.g., Family-owned plumbing company serving the greater Portland area for 25 years..."},
                        {"key": "success_vision", "label": "Business goals?", "type": "textarea", "placeholder": "e.g., 20 new leads per month, expand to 3 more zip codes, hire 2 more technicians..."},
                        {"key": "one_thing", "label": "Why do customers choose you over competitors?", "type": "input", "placeholder": "e.g., Same-day emergency service, transparent pricing, 5-star Google rating"},
                    ],
                },
                {
                    "step": 2, "step_title": "Customers & Trust", "step_description": "Who calls you and why?",
                    "fields": [
                        {"key": "ideal_audience", "label": "Your typical customer?", "type": "textarea", "placeholder": "e.g., Homeowners 35-65, dual income, value quality over lowest price..."},
                        {"key": "audience_journey", "label": "How do they find you?", "type": "textarea", "placeholder": "e.g., Google Maps, neighbor referrals, Nextdoor, yard signs..."},
                        {"key": "primary_action", "label": "What should they do?", "type": "input", "placeholder": "e.g., Call for free estimate, fill out contact form, book online"},
                    ],
                },
                {
                    "step": 3, "step_title": "Brand & Image", "step_description": "How your business presents itself.",
                    "fields": [
                        {"key": "brand_personality", "label": "Your business personality?", "type": "textarea", "placeholder": "e.g., Reliable neighbor who shows up on time, explains everything clearly, stands behind their work..."},
                        {"key": "color_palette", "label": "Color Palette Feel", "type": "select", "options": ["", "Warm & Inviting", "Cool & Professional", "Earthy & Natural", "Bold & Vibrant", "Monochromatic & Minimalist", "Dark & Moody"]},
                        {"key": "visual_style", "label": "Visual Style", "type": "select", "options": ["", "Minimalist & Clean", "Corporate & Professional", "Playful & Creative", "Elegant & Luxurious", "Tech & Futuristic", "Rustic & Handmade"]},
                        {"key": "core_values", "label": "Business values?", "type": "input", "placeholder": "e.g., Integrity, punctuality, fair pricing"},
                        {"key": "desired_feeling", "label": "What should visitors feel?", "type": "input", "placeholder": "e.g., These are the pros I can trust with my home"},
                    ],
                },
                {
                    "step": 4, "step_title": "Differentiators", "step_description": "Stand out from the competition.",
                    "fields": [
                        {"key": "key_features", "label": "Services to highlight?", "type": "textarea", "placeholder": "e.g., Emergency 24/7, free estimates, senior discounts, licensed & insured, warranty on all work..."},
                        {"key": "sites_loved", "label": "Local business sites you like?", "type": "textarea", "placeholder": "e.g., Any local competitor with good Google reviews and clean site..."},
                        {"key": "future_vision", "label": "Growth plans?", "type": "textarea", "placeholder": "e.g., Add commercial services, franchise model, training academy..."},
                        {"key": "additional_notes", "label": "Anything else?", "type": "input", "placeholder": "Licenses, certifications, awards, years in business"},
                    ],
                },
            ],
            "prompt_overrides": {
                "global_tone": "Write for a local service business. Be warm, trustworthy, and community-focused. Emphasize reliability, experience, and personal touch. Include local references where possible. Optimize for local SEO.",
            },
            "visual_defaults": {"color_scheme": "brand", "card_style": "elevated", "animation": "fade-in", "layout": "single-scroll"},
            "meta": {"version": "1.0", "compatible_depths": ["minimal", "standard", "comprehensive", "legendary"]},
        },
    },
]


def slugify(name):
    return re.sub(r'[^a-z0-9]+', '-', name.lower()).strip('-')


def validate_profile_config(config):
    errors = []
    if not isinstance(config, dict):
        return ["Config must be a JSON object"]
    if "sections" not in config or not isinstance(config.get("sections"), list):
        errors.append("Config must contain 'sections' array")
    if "discovery_fields" not in config or not isinstance(config.get("discovery_fields"), list):
        errors.append("Config must contain 'discovery_fields' array")
    if "depth_presets" in config:
        dp = config["depth_presets"]
        if not isinstance(dp, dict):
            errors.append("'depth_presets' must be an object")
        else:
            for key, preset in dp.items():
                if "sections" not in preset:
                    errors.append(f"Depth preset '{key}' must contain 'sections'")
                if "content_multiplier" not in preset:
                    errors.append(f"Depth preset '{key}' must contain 'content_multiplier'")
    for i, step in enumerate(config.get("discovery_fields", [])):
        if "fields" not in step:
            errors.append(f"Discovery step {i+1} must contain 'fields'")
    return errors


def get_sections_for_profile(profile_config, depth="comprehensive"):
    presets = profile_config.get("depth_presets", CONTENT_DEPTH_PRESETS)
    preset = presets.get(depth, presets.get("standard", {"sections": profile_config.get("sections", []), "content_multiplier": 1.0}))
    enabled_keys = preset.get("sections", [])
    all_sections = copy.deepcopy(DEFAULT_SECTIONS)
    profile_sections = profile_config.get("sections", [s["key"] for s in all_sections])
    result = []
    for section in all_sections:
        if section["key"] in profile_sections:
            section["enabled"] = section["key"] in enabled_keys
            result.append(section)
    return result, preset.get("content_multiplier", 1.0)
