"""Intent analyzer for workflow detection."""

from __future__ import annotations

import json
import re
from dataclasses import dataclass
from typing import Optional

from ..utils.logger import Logger


@dataclass
class WorkflowStep:
    order: int
    skill: str
    task: str
    purpose: str
    depends_on: Optional[int] = None


@dataclass
class WorkflowAnalysis:
    is_workflow: bool
    primary_intent: str
    steps: list[WorkflowStep]
    estimated_time: str
    can_parallelize: bool


class IntentAnalyzer:
    """Analyzes user intent and detects workflows."""

    SYSTEM_PROMPT = """You are an intent analyzer for a marketing assistant.  # noqa: E501
Your job is to analyze user requests and identify if they need multiple skills to complete.

Available Skills:
- copywriting: Write website copy, landing pages, blog posts, product descriptions
- seo-audit: Technical SEO review, on-page optimization, keyword analysis
- social-content: Create Twitter, LinkedIn, social media posts
- email-sequence: Email campaigns, onboarding sequences
- web-scrape: Scrape websites for research, competitor analysis
- brand_consistency_check: Validate content against brand guidelines
- content_refine: Refine and improve existing content
- changelog_to_marketing: Convert changelogs to marketing content
- blog_generate_with_images: Generate blog posts with images
- web_search: Search web and scrape results
- web_extract: Extract structured data from websites
- web_crawl: Crawl entire websites
- auto_distribution_plan: Plan content distribution strategy
- content_import: Import content from URL (Twitter, blogs, etc.)
- content_remix: Remix imported content using angle templates
- draft_submission: Create and submit draft for approval
- draft_status_check: Check draft approval status
- publish_content: Publish approved content

Special Intent Patterns to Detect:
1. "Remix/COPY content from URL" → content_import → content_remix → brand_consistency_check → draft_submission
2. "Import this tweet/article" → content_import → (optional: content_remix)
3. "Scrape/extract from URL" → web-scrape or web_extract
4. "Check this content for brand" → brand_consistency_check
5. "Submit a draft" → draft_submission
6. "Check status of draft" → draft_status_check
7. "Publish draft" → publish_content

Response Format (JSON only):
{
  "isWorkflow": true/false,
  "primaryIntent": "main goal in 5-10 words",
  "steps": [
    {
      "order": 1,
      "skill": "skill_name",
      "task": "specific task description",
      "purpose": "why this step is needed",
      "dependsOn": null or number
    }
  ],
  "estimatedTime": "e.g., 2-3 minutes",
  "canParallelize": false
}

Rules:
1. If request needs 2+ distinct skills → isWorkflow: true
2. Order matters: research → create → validate → distribute
3. Steps can depend on previous steps (use dependsOn)
4. Be specific in task descriptions

Examples:

Input: "Write a blog about stablecoins"
Output: {
  "isWorkflow": false,
  "primaryIntent": "Write blog post about stablecoins",
  "steps": [
    {"order": 1, "skill": "copywriting", "task": "Write blog post",
     "purpose": "Create content", "dependsOn": null}
  ],
  "estimatedTime": "1 minute",
  "canParallelize": false
}

Input: "Write blog about crypto then check SEO and create tweets"
Output: {
  "isWorkflow": true,
  "primaryIntent": "Create blog with SEO optimization and social promotion",
  "steps": [
    {"order": 1, "skill": "copywriting", "task": "Write blog post",
     "purpose": "Create content", "dependsOn": null},
    {"order": 2, "skill": "seo-audit", "task": "Check SEO",
     "purpose": "SEO check", "dependsOn": 1},
    {"order": 3, "skill": "social-content", "task": "Create Twitter posts",
     "purpose": "Social promo", "dependsOn": 1}
  ],
  "estimatedTime": "3-4 minutes",
  "canParallelize": false
}

Input: "Scrape competitor blog and write better content"
Output: {
  "isWorkflow": true,
  "primaryIntent": "Research competitor and create superior content",
  "steps": [
    {"order": 1, "skill": "web-scrape", "task": "Scrape competitor blog",
     "purpose": "Research", "dependsOn": null},
    {"order": 2, "skill": "copywriting", "task": "Write improved version",
     "purpose": "Create content", "dependsOn": 1}
  ],
  "estimatedTime": "2-3 minutes",
  "canParallelize": false
}

Input: "Remix content from https://x.com/elonmusk/status/123 for reply.cash and submit a draft"
Output: {
  "isWorkflow": true,
  "primaryIntent": "Import tweet, remix with angle, and submit draft",
  "steps": [
    {"order": 1, "skill": "content_import", "task": "Import content from https://x.com/elonmusk/status/123",
     "purpose": "Extract source content", "dependsOn": null},
    {"order": 2, "skill": "content_remix", "task": "Remix imported content with appropriate angle for reply.cash",
     "purpose": "Transform content for our brand", "dependsOn": 1},
    {"order": 3, "skill": "brand_consistency_check", "task": "Check remixed content against brand guidelines",
     "purpose": "Validate brand alignment", "dependsOn": 2},
    {"order": 4, "skill": "draft_submission", "task": "Create and submit draft for approval",
     "purpose": "Submit for human review", "dependsOn": 3}
  ],
  "estimatedTime": "3-4 minutes",
  "canParallelize": false
}

Input: "Copy this tweet https://x.com/user/status/456 using the Africa Focus angle and create a blog draft"
Output: {
  "isWorkflow": true,
  "primaryIntent": "Import tweet with specific angle and create draft",
  "steps": [
    {"order": 1, "skill": "content_import", "task": "Import tweet from https://x.com/user/status/456",
     "purpose": "Extract tweet content", "dependsOn": null},
    {"order": 2, "skill": "content_remix", "task": "Remix using angle_preset_africa_focus angle for blog format",
     "purpose": "Remix with Africa Focus angle", "dependsOn": 1},
    {"order": 3, "skill": "draft_submission", "task": "Create blog draft from remixed content",
     "purpose": "Submit for approval", "dependsOn": 2}
  ],
  "estimatedTime": "2-3 minutes",
  "canParallelize": false
}

Input: "Import this article https://example.com/blog and check if it matches our brand"
Output: {
  "isWorkflow": true,
  "primaryIntent": "Import article and validate brand alignment",
  "steps": [
    {"order": 1, "skill": "content_import", "task": "Import article from https://example.com/blog",
     "purpose": "Extract article content", "dependsOn": null},
    {"order": 2, "skill": "brand_consistency_check", "task": "Check imported content against brand guidelines",
     "purpose": "Validate brand alignment", "dependsOn": 1}
  ],
  "estimatedTime": "1-2 minutes",
  "canParallelize": false
}"""

    def __init__(self, provider_manager) -> None:
        self.provider_manager = provider_manager

    def analyze_intent(self, user_input: str) -> WorkflowAnalysis:
        """Analyze user intent for workflow detection."""
        Logger.info("Analyzing intent for workflow detection", {"input": user_input[:100]})

        try:
            response = self.provider_manager.execute(
                "", user_input, {"systemPrompt": self.SYSTEM_PROMPT, "skill": "intent-analysis"}
            )

            # Parse JSON from response
            json_match = re.search(r"\{[\s\S]*\}", response)
            if not json_match:
                raise ValueError("Invalid analysis format")

            analysis_data = json.loads(json_match.group())

            steps = [
                WorkflowStep(
                    order=s["order"],
                    skill=s["skill"],
                    task=s["task"],
                    purpose=s["purpose"],
                    depends_on=s.get("dependsOn"),
                )
                for s in analysis_data.get("steps", [])
            ]

            # If no steps returned, fallback to copywriting
            if not steps:
                steps = [
                    WorkflowStep(
                        order=1,
                        skill="copywriting",
                        task=user_input,
                        purpose="Handle request",
                        depends_on=None,
                    )
                ]

            analysis = WorkflowAnalysis(
                is_workflow=analysis_data.get("isWorkflow", False),
                primary_intent=analysis_data.get("primaryIntent", user_input),
                steps=steps,
                estimated_time=analysis_data.get("estimatedTime", "1 minute"),
                can_parallelize=analysis_data.get("canParallelize", False),
            )

            Logger.info(
                "Intent analysis complete",
                {"isWorkflow": analysis.is_workflow, "stepCount": len(analysis.steps)},
            )

            return analysis

        except Exception as e:
            Logger.error("Intent analysis failed", e)

            # Fallback: single skill - copywriting for general queries
            return WorkflowAnalysis(
                is_workflow=False,
                primary_intent=user_input,
                steps=[
                    WorkflowStep(
                        order=1,
                        skill="copywriting",
                        task=user_input,
                        purpose="Handle request",
                        depends_on=None,
                    )
                ],
                estimated_time="1 minute",
                can_parallelize=False,
            )

    def format_workflow_for_display(self, analysis: WorkflowAnalysis) -> str:
        """Format workflow analysis for display."""
        if not analysis.is_workflow or len(analysis.steps) == 1:
            return f"I'll help you with: {analysis.primary_intent}"

        lines = ["I'll perform the following workflow:\n"]

        for i, step in enumerate(analysis.steps):
            icon = self._get_skill_icon(step.skill)
            lines.append(f"{i + 1}. {icon}  {step.skill}")
            lines.append(f"   {step.task}")
            if step.depends_on:
                lines.append(f"   (depends on step {step.depends_on})")
            lines.append("")

        return "\n".join(lines)

    def _get_skill_icon(self, skill: str) -> str:
        """Get icon for skill."""
        icons = {
            "copywriting": "✍️",
            "seo-audit": "🔍",
            "social-content": "📱",
            "email-sequence": "📧",
            "web-scrape": "🕷️",
            "web_search": "🔎",
            "web_extract": "📊",
            "web_crawl": "🕸️",
            "brand_consistency_check": "✅",
            "content_refine": "✨",
            "changelog_to_marketing": "📝",
            "blog_generate_with_images": "🖼️",
            "auto_distribution_plan": "📢",
            "content_import": "📥",
            "content_remix": "🔄",
            "draft_submission": "📋",
            "draft_status_check": "📊",
            "publish_content": "🚀",
        }
        return icons.get(skill, "⚙️")
