"""Draft management for content submission and approval workflow."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Optional

from ..utils.logger import Logger

if TYPE_CHECKING:
    from .api_client import ApiClient


@dataclass
class DraftContent:
    """Content for a draft."""

    title: str
    body: str
    description: str = ""  # Plain text description/summary
    category: str = ""
    tags: list[str] = field(default_factory=list)
    seo: dict = field(default_factory=dict)


@dataclass
class DraftResult:
    """Result of draft submission."""

    success: bool
    draft_id: Optional[str] = None
    approval_token: Optional[str] = None
    approval_url: Optional[str] = None
    frontend_url: Optional[str] = None
    error: Optional[str] = None


@dataclass
class DraftStatus:
    """Status of a draft."""

    draft_id: str
    status: str  # "draft", "pending", "approved", "rejected"
    feedback: Optional[str] = None
    submitted_at: Optional[str] = None
    reviewed_at: Optional[str] = None


class DraftManager:
    """Manages content drafts and approval workflow."""

    def __init__(self, api_client: "ApiClient", agent_id: str) -> None:
        self.api_client = api_client
        self.agent_id = agent_id

    def submit_draft(
        self,
        content: DraftContent,
        channel: str = "blog",
    ) -> DraftResult:
        """Submit content as a draft for approval.

        Args:
            content: The draft content
            channel: Channel to publish to (blog, social, email)

        Returns:
            DraftResult with draft ID and approval URL
        """
        Logger.info("Submitting draft", {"title": content.title, "channel": channel})

        try:
            # Build payload
            payload = {
                "channel": channel,
                "content": {
                    "title": content.title,
                    "body": content.body,
                    "description": content.description or "",
                    "category": content.category or "General",
                    "tags": content.tags,
                },
            }

            if content.seo:
                payload["content"]["seo"] = content.seo

            response = self.api_client.post(
                "/skills/marketing/submit-draft",
                payload,
            )

            if response.success and response.data:
                data = response.data
                draft_id = data.get("draftId") or data.get("id")
                approval_token = data.get("approvalToken")

                # Build frontend URLs
                base_url = "https://reply-marketingz.vercel.app"
                approval_url = None
                if draft_id and approval_token:
                    approval_url = f"{base_url}/approval/draft/{draft_id}?token={approval_token}"

                frontend_url = f"{base_url}/approval/drafts/{self.agent_id}"

                Logger.info("Draft submitted successfully", {"draft_id": draft_id})

                return DraftResult(
                    success=True,
                    draft_id=draft_id,
                    approval_token=approval_token,
                    approval_url=approval_url,
                    frontend_url=frontend_url,
                )

            return DraftResult(
                success=False,
                error=response.error or "Unknown error submitting draft",
            )

        except Exception as e:
            Logger.error("Failed to submit draft", e)
            return DraftResult(success=False, error=str(e))

    def request_approval(self, draft_id: str) -> DraftResult:
        """Request approval for a draft.

        Args:
            draft_id: The draft ID

        Returns:
            DraftResult with approval URL
        """
        Logger.info("Requesting approval", {"draft_id": draft_id})

        try:
            response = self.api_client.post(
                f"/drafts/{draft_id}/submit-approval",
                {},
            )

            if response.success and response.data:
                data = response.data
                # Backend returns 'token' not 'approvalToken'
                approval_token = data.get("token") or data.get("approvalToken")

                base_url = "https://reply-marketingz.vercel.app"
                approval_url = None
                if approval_token:
                    approval_url = f"{base_url}/approval/draft/{draft_id}?token={approval_token}"

                return DraftResult(
                    success=True,
                    draft_id=draft_id,
                    approval_token=approval_token,
                    approval_url=approval_url,
                )

            return DraftResult(
                success=False,
                error=response.error or "Unknown error requesting approval",
            )

        except Exception as e:
            Logger.error("Failed to request approval", e)
            return DraftResult(success=False, error=str(e))

    def get_draft_status(self, draft_id: str) -> Optional[DraftStatus]:
        """Get the status of a draft.

        Args:
            draft_id: The draft ID

        Returns:
            DraftStatus with current status
        """
        try:
            response = self.api_client.get(f"/drafts/{draft_id}")

            if response.success and response.data:
                data = response.data
                return DraftStatus(
                    draft_id=draft_id,
                    status=data.get("status", "unknown"),
                    feedback=data.get("feedback"),
                    submitted_at=data.get("submittedAt"),
                    reviewed_at=data.get("reviewedAt"),
                )

            return None

        except Exception as e:
            Logger.error("Failed to get draft status", e)
            return None

    def list_drafts(self) -> list[dict]:
        """Get all drafts for this agent.

        Returns:
            List of draft dictionaries with full details
        """
        try:
            response = self.api_client.get("/drafts")

            if response.success and response.data:
                drafts = response.data if isinstance(response.data, list) else response.data.get("drafts", [])
                # Return raw draft data with title extracted from content if needed
                result = []
                for draft in drafts:
                    draft_data = {
                        "draftId": draft.get("id") or draft.get("draftId", "unknown"),
                        "status": draft.get("status", "unknown"),
                        "title": "Untitled",
                        "createdAt": draft.get("createdAt") or draft.get("submittedAt"),
                        "feedback": draft.get("feedback"),
                    }
                    # Extract title from content if available
                    content = draft.get("content", {})
                    if isinstance(content, dict):
                        draft_data["title"] = content.get("title", "Untitled")
                    result.append(draft_data)
                return result

            return []

        except Exception as e:
            Logger.error("Failed to list drafts", e)
            return []

    def update_draft(
        self,
        draft_id: str,
        content: DraftContent,
    ) -> DraftResult:
        """Update an existing draft.

        Args:
            draft_id: The draft ID
            content: Updated content

        Returns:
            DraftResult with updated draft info
        """
        Logger.info("Updating draft", {"draft_id": draft_id})

        try:
            payload = {
                "content": {
                    "title": content.title,
                    "body": content.body,
                    "category": content.category,
                    "tags": content.tags,
                },
            }

            if content.seo:
                payload["content"]["seo"] = content.seo

            response = self.api_client.put(
                f"/drafts/{draft_id}",
                payload,
            )

            if response.success:
                return DraftResult(success=True, draft_id=draft_id)

            return DraftResult(
                success=False,
                draft_id=draft_id,
                error=response.error or "Unknown error updating draft",
            )

        except Exception as e:
            Logger.error("Failed to update draft", e)
            return DraftResult(success=False, draft_id=draft_id, error=str(e))

    def refine_content(
        self,
        draft_id: str,
        feedback: list[str],
    ) -> Optional[str]:
        """Refine content based on feedback.

        Args:
            draft_id: The draft ID
            feedback: List of feedback items

        Returns:
            Refined content or None if failed
        """
        Logger.info("Refining content", {"draft_id": draft_id})

        try:
            response = self.api_client.post(
                "/skills/content/refine",
                {
                    "draftId": draft_id,
                    "feedback": feedback,
                },
            )

            if response.success and response.data:
                return response.data.get("refinedContent")

            return None

        except Exception as e:
            Logger.error("Failed to refine content", e)
            return None

    def publish(self, draft_id: str, channel: str = "blog") -> DraftResult:
        """Publish an approved draft.

        Args:
            draft_id: The draft ID
            channel: Channel to publish to

        Returns:
            DraftResult with publish status
        """
        Logger.info("Publishing draft", {"draft_id": draft_id, "channel": channel})

        try:
            response = self.api_client.post(
                "/skills/marketing/publish",
                {
                    "draftId": draft_id,
                    "channel": channel,
                },
            )

            if response.success:
                return DraftResult(success=True, draft_id=draft_id)

            return DraftResult(
                success=False,
                draft_id=draft_id,
                error=response.error or "Unknown error publishing",
            )

        except Exception as e:
            Logger.error("Failed to publish", e)
            return DraftResult(success=False, draft_id=draft_id, error=str(e))

    def format_draft_result(self, result: DraftResult) -> str:
        """Format draft result for display."""
        if not result.success:
            return f"❌ Failed: {result.error}"

        lines = [
            "✅ Draft submitted successfully!",
            "",
            f"Draft ID: {result.draft_id}",
        ]

        if result.approval_url:
            lines.extend([
                "",
                "🔗 Approval URL:",
                f"   {result.approval_url}",
            ])

        if result.frontend_url:
            lines.extend([
                "",
                "📋 View all drafts:",
                f"   {result.frontend_url}",
            ])

        lines.extend([
            "",
            "⏳ Next steps:",
            "   1. Share the approval URL with reviewers",
            "   2. Wait for approval",
            "   3. Content will be published after approval",
        ])

        return "\n".join(lines)
