import json
import logging
from app.services.llm import call_llm, call_llm_text

logger = logging.getLogger(__name__)

AUGMENT_TYPES = {
    "estimator": {
        "label": "Cost Estimator",
        "description": "Interactive calculator that helps visitors estimate costs for products or services",
        "icon": "calculator"
    },
    "assessment": {
        "label": "Self-Assessment Quiz",
        "description": "Interactive quiz that evaluates visitor needs and recommends solutions",
        "icon": "clipboard-check"
    },
    "comparison": {
        "label": "Product Comparator",
        "description": "Side-by-side comparison tool for evaluating options",
        "icon": "columns"
    },
    "roi_calculator": {
        "label": "ROI Calculator",
        "description": "Return on investment calculator showing financial benefits",
        "icon": "trending-up"
    },
    "configurator": {
        "label": "Product Configurator",
        "description": "Build-your-own tool that lets visitors customize a product or service package",
        "icon": "sliders"
    },
    "checklist": {
        "label": "Interactive Checklist",
        "description": "Step-by-step guided checklist for planning or decision-making",
        "icon": "check-square"
    }
}

SYSTEM_PROMPT = """You are an expert interactive widget designer and developer. You create high-value, niche-specific interactive tools that engage visitors, capture leads, and demonstrate expertise. Your widgets are professional, visually polished, and provide genuine value to the user.

You generate complete, self-contained HTML widgets with embedded CSS and JavaScript. The widgets must:
1. Be fully self-contained (no external dependencies except Font Awesome CDN for icons)
2. Use modern, professional design with smooth animations and dimensional depth (layered shadows, inner highlights, subtle gradients)
3. Be responsive and work on all screen sizes
4. Include tooltips on interactive elements
5. Calculate real, useful results based on actual industry data
6. Use EXACTLY the brand colors provided — match the site's color palette precisely (primary, secondary, accent). Use a LIGHT background theme (#ffffff / #f8fafc / #f1f5f9) with brand-colored accents, NOT a dark theme, unless dark theme is explicitly requested. Cards should have layered box-shadows with inset highlights for 3D depth.
7. Include proper form validation and user feedback
8. Have a polished results display with breakdowns and visualizations
9. Use CSS variables for colors: --widget-primary, --widget-secondary, --widget-accent set to the exact hex values provided
10. Buttons should use gradient backgrounds from primary to secondary color with inner highlight shadows for a dimensional feel"""


def get_augment_types():
    return AUGMENT_TYPES


def suggest_augments(niche: str, niche_data: dict = None) -> list:
    niche_desc = ""
    if niche_data:
        niche_desc = f"""
Niche details:
- Name: {niche_data.get('name', niche)}
- Description: {niche_data.get('description', '')}
- Monetization: {niche_data.get('monetization_model', '')}
- Target Audience: {niche_data.get('target_audience', '')}"""

    prompt = f"""For a business in the "{niche}" niche, suggest 3-5 high-value interactive widgets that would engage visitors and demonstrate expertise.
{niche_desc}

For each widget, provide ALL of these fields:
- "type": one of {json.dumps(list(AUGMENT_TYPES.keys()))}
- "title": specific, compelling title for this widget (e.g., "Luxury Pool Cost Estimator" not just "Cost Estimator")
- "description": 2-3 sentences explaining what it does and why it's valuable for visitors
- "value_proposition": one sentence on how this widget converts visitors into leads/customers
- "target_audience": who specifically benefits from this widget (e.g., "Homeowners planning a kitchen remodel", "Small business owners evaluating CRM options")
- "benefit_level": rate 1-5 how beneficial this is to the business (5 = highest conversion impact)
- "benefit_reason": one sentence explaining WHY this is beneficial and to whom (e.g., "Highest conversion tool because price-conscious buyers need cost clarity before committing")
- "category": one of ["lead_capture", "trust_builder", "decision_aid", "engagement", "education"]

Return JSON array sorted by benefit_level descending (most beneficial first):
[
  {{"type": "...", "title": "...", "description": "...", "value_proposition": "...", "target_audience": "...", "benefit_level": 5, "benefit_reason": "...", "category": "..."}}
]"""

    try:
        response = call_llm(prompt, SYSTEM_PROMPT)
        parsed = json.loads(response)
        if isinstance(parsed, list):
            return parsed
        if isinstance(parsed, dict):
            for key in ("suggestions", "widgets", "items", "results", "augments"):
                if key in parsed and isinstance(parsed[key], list):
                    return parsed[key]
            vals = list(parsed.values())
            if vals and isinstance(vals[0], list):
                return vals[0]
    except (json.JSONDecodeError, Exception) as e:
        logger.error(f"Augment suggestion failed: {e}")
    return []


def generate_augment_html(augment_type: str, title: str, niche: str,
                          brand_data: dict = None, niche_data: dict = None,
                          custom_instructions: str = "") -> dict:
    brand_colors = ""
    brand_name = ""
    if brand_data:
        brand_name = "Business"
        opts = brand_data.get("options", [])
        rec = brand_data.get("recommended", 0)
        if opts and rec < len(opts):
            brand_name = opts[rec].get("name", "Business")
        brand_colors = f"""
Brand Colors:
- Primary: {brand_data.get('color_primary', '#6366f1')}
- Secondary: {brand_data.get('color_secondary', '#8b5cf6')}
- Accent: {brand_data.get('color_accent', '#22d3ee')}
Brand Name: {brand_name}"""

    niche_desc = ""
    if niche_data:
        niche_desc = f"""
Niche details:
- Description: {niche_data.get('description', '')}
- Target Audience: {niche_data.get('target_audience', '')}
- Monetization: {niche_data.get('monetization_model', '')}"""

    type_info = AUGMENT_TYPES.get(augment_type, {})
    type_label = type_info.get("label", augment_type)

    primary_hex = brand_data.get('color_primary', '#6366f1') if brand_data else '#6366f1'
    secondary_hex = brand_data.get('color_secondary', '#8b5cf6') if brand_data else '#8b5cf6'
    accent_hex = brand_data.get('color_accent', '#22d3ee') if brand_data else '#22d3ee'

    prompt = f"""Create a complete, self-contained HTML widget for "{title}" - a {type_label} for the "{niche}" niche.
{brand_colors}
{niche_desc}
{f'Additional instructions: {custom_instructions}' if custom_instructions else ''}

CRITICAL COLOR REQUIREMENTS — the widget will be embedded in a site that uses these EXACT colors:
- Primary: {primary_hex}  (use for headings, primary buttons, key accents)
- Secondary: {secondary_hex}  (use for secondary elements, gradients paired with primary)
- Accent: {accent_hex}  (use for highlights, links, call-outs)
- Background: #ffffff (main) / #f8fafc (sections) / #f1f5f9 (alternating)
- Text: #111827 (headings) / #374151 (body) / #6b7280 (muted)
- Cards: white background with layered box-shadows (e.g. box-shadow: 0 1px 2px rgba(0,0,0,0.04), 0 4px 12px -2px rgba(0,0,0,0.06), inset 0 1px 0 rgba(255,255,255,0.8))
- Buttons: background gradient from {primary_hex} to {secondary_hex}, white text, with box-shadow including inset highlight
DO NOT use a dark/black background. This is a LIGHT-themed widget.

REQUIREMENTS:
1. Generate a COMPLETE standalone HTML document with embedded <style> and <script> tags
2. Use the EXACT brand colors above — light background, brand-colored accents
3. Include Font Awesome CDN for icons: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
4. Make it fully responsive
5. Include realistic industry-accurate data, pricing, and calculations
6. Add smooth animations and transitions with dimensional depth (layered shadows, inner glows)
7. Include tooltips on key elements using title attributes
8. The widget should provide REAL VALUE - actual useful calculations/results
9. Include a results section that shows detailed breakdowns
10. Add a subtle branded footer with the brand name
11. Set CSS variables: --widget-primary: {primary_hex}; --widget-secondary: {secondary_hex}; --widget-accent: {accent_hex};
12. Maximum width of 800px, centered on page
13. Alternating table/list rows should use #f8fafc vs #ffffff for clear visual separation

WIDGET TYPE SPECIFICS FOR {type_label.upper()}:
{"- Multiple form sections with dropdowns, checkboxes, and range inputs" if augment_type == "estimator" else ""}
{"- Multiple form sections with select dropdowns, checkbox groups for features/add-ons" if augment_type == "configurator" else ""}
{"- Series of multiple-choice questions with weighted scoring" if augment_type == "assessment" else ""}
{"- Side-by-side cards with feature comparison matrix" if augment_type == "comparison" else ""}
{"- Input fields for costs, revenue, timeframe with visual ROI chart" if augment_type == "roi_calculator" else ""}
{"- Expandable sections with checkboxes and progress tracking" if augment_type == "checklist" else ""}
- Show a detailed results section when the user submits/completes the widget
- Results should include specific numbers, recommendations, and next steps
- Include a call-to-action in the results section

Return ONLY the complete HTML document, nothing else. No markdown code fences. Start with <!DOCTYPE html> and end with </html>."""

    html_content = ""
    last_error = None
    for attempt in range(3):
        try:
            response = call_llm_text(prompt, SYSTEM_PROMPT, max_tokens=16384)
            candidate = response.strip()
            if candidate.startswith("```html"):
                candidate = candidate[len("```html"):].strip()
            if candidate.startswith("```"):
                candidate = candidate[3:].strip()
            if candidate.endswith("```"):
                candidate = candidate[:-3].strip()

            if not candidate.startswith("<!DOCTYPE") and not candidate.startswith("<html"):
                doc_start = candidate.find("<!DOCTYPE")
                if doc_start == -1:
                    doc_start = candidate.find("<html")
                if doc_start >= 0:
                    candidate = candidate[doc_start:]

            if candidate and len(candidate) >= 100:
                html_content = candidate
                break
            else:
                last_error = f"AI returned insufficient HTML (got {len(candidate)} chars)"
                logger.warning(f"Augment generate attempt {attempt+1}/3: {last_error}, retrying...")
        except Exception as e:
            last_error = str(e)
            logger.warning(f"Augment generate attempt {attempt+1}/3 error: {last_error}, retrying...")

    if not html_content or len(html_content) < 100:
        raise ValueError(f"AI returned empty or insufficient HTML content after 3 attempts. Last error: {last_error}")

    config = {
        "type": augment_type,
        "type_label": type_label,
        "title": title,
        "niche": niche,
        "brand_name": brand_name,
        "brand_colors": {
            "primary": brand_data.get("color_primary", "#6366f1") if brand_data else "#6366f1",
            "secondary": brand_data.get("color_secondary", "#8b5cf6") if brand_data else "#8b5cf6",
            "accent": brand_data.get("color_accent", "#22d3ee") if brand_data else "#22d3ee"
        }
    }

    return {
        "html_content": html_content,
        "config": config,
        "title": title,
        "description": f"{type_label} for {niche}",
        "augment_type": augment_type
    }
