"""Export functionality for best prompts (HTML, Gist)."""

from __future__ import annotations

import json
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Any


PromptData = dict[str, Any]


HTML_TEMPLATE = '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Best Prompts - Claude-X</title>
    <style>
        :root {{
            --bg: #0d1117;
            --card-bg: #161b22;
            --border: #30363d;
            --text: #c9d1d9;
            --text-muted: #8b949e;
            --accent: #58a6ff;
            --success: #3fb950;
            --warning: #d29922;
        }}

        * {{
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }}

        body {{
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.6;
            padding: 2rem;
        }}

        .container {{
            max-width: 900px;
            margin: 0 auto;
        }}

        h1 {{
            font-size: 2rem;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }}

        .subtitle {{
            color: var(--text-muted);
            margin-bottom: 2rem;
        }}

        .stats {{
            display: flex;
            gap: 2rem;
            margin-bottom: 2rem;
            padding: 1rem;
            background: var(--card-bg);
            border-radius: 8px;
            border: 1px solid var(--border);
        }}

        .stat {{
            text-align: center;
        }}

        .stat-value {{
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--accent);
        }}

        .stat-label {{
            font-size: 0.875rem;
            color: var(--text-muted);
        }}

        .prompt-card {{
            background: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 8px;
            margin-bottom: 1.5rem;
            overflow: hidden;
        }}

        .prompt-header {{
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            border-bottom: 1px solid var(--border);
        }}

        .prompt-meta {{
            display: flex;
            gap: 1rem;
            align-items: center;
        }}

        .score {{
            background: var(--success);
            color: #000;
            padding: 0.25rem 0.75rem;
            border-radius: 999px;
            font-weight: bold;
            font-size: 0.875rem;
        }}

        .score.medium {{
            background: var(--warning);
        }}

        .category {{
            color: var(--text-muted);
            font-size: 0.875rem;
        }}

        .prompt-content {{
            padding: 1rem;
        }}

        .prompt-text {{
            background: var(--bg);
            padding: 1rem;
            border-radius: 6px;
            font-family: "SF Mono", Monaco, Consolas, monospace;
            font-size: 0.875rem;
            white-space: pre-wrap;
            word-break: break-word;
        }}

        .prompt-stats {{
            display: flex;
            gap: 1.5rem;
            padding: 1rem;
            border-top: 1px solid var(--border);
            color: var(--text-muted);
            font-size: 0.875rem;
        }}

        .footer {{
            text-align: center;
            color: var(--text-muted);
            font-size: 0.875rem;
            margin-top: 3rem;
            padding-top: 2rem;
            border-top: 1px solid var(--border);
        }}

        .footer a {{
            color: var(--accent);
            text-decoration: none;
        }}

        .footer a:hover {{
            text-decoration: underline;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>My Best Prompts</h1>
        <p class="subtitle">Generated by Claude-X on {generated_date}</p>

        <div class="stats">
            <div class="stat">
                <div class="stat-value">{total_prompts}</div>
                <div class="stat-label">Total Prompts</div>
            </div>
            <div class="stat">
                <div class="stat-value">{avg_score:.1f}</div>
                <div class="stat-label">Avg Score</div>
            </div>
            <div class="stat">
                <div class="stat-value">{top_category}</div>
                <div class="stat-label">Top Category</div>
            </div>
        </div>

        {prompt_cards}

        <div class="footer">
            <p>Generated with <a href="https://github.com/kakao-lucas-ms/claude-x">Claude-X</a></p>
        </div>
    </div>
</body>
</html>
'''

PROMPT_CARD_TEMPLATE = '''
<div class="prompt-card">
    <div class="prompt-header">
        <div class="prompt-meta">
            <span class="score{score_class}">{score:.1f}/10</span>
            <span class="category">{category}</span>
        </div>
        <span class="date">{date}</span>
    </div>
    <div class="prompt-content">
        <div class="prompt-text">{prompt_text}</div>
    </div>
    <div class="prompt-stats">
        <span>Structure: {structure_score:.1f}</span>
        <span>Context: {context_score:.1f}</span>
        <span>Project: {project}</span>
    </div>
</div>
'''


def export_to_html(prompts: list[PromptData], output_path: str | None = None) -> str:
    """Export prompts to HTML file.

    Args:
        prompts: List of prompt data dictionaries.
        output_path: Output file path. If None, returns HTML string.

    Returns:
        Path to generated file or HTML string.
    """
    if not prompts:
        return _generate_empty_html()

    # Calculate stats
    total = len(prompts)
    avg_score = sum(_get_combined_score(p) for p in prompts) / total

    # Get top category
    categories: dict[str, int] = {}
    for p in prompts:
        cat = p.get("category", "Unknown")
        categories[cat] = categories.get(cat, 0) + 1
    top_category = max(categories, key=categories.get) if categories else "N/A"

    # Generate prompt cards
    cards = []
    for prompt in prompts:
        score = _get_combined_score(prompt)
        score_class = "" if score >= 7 else " medium"

        card = PROMPT_CARD_TEMPLATE.format(
            score=score,
            score_class=score_class,
            category=prompt.get("category", "Unknown"),
            date=prompt.get("created_at", "")[:10] if prompt.get("created_at") else "N/A",
            prompt_text=_escape_html(prompt.get("first_prompt", "")),
            structure_score=prompt.get("structure_score", 0),
            context_score=prompt.get("context_score", 0),
            project=prompt.get("project", "Unknown"),
        )
        cards.append(card)

    # Generate final HTML
    html = HTML_TEMPLATE.format(
        generated_date=datetime.now().strftime("%Y-%m-%d %H:%M"),
        total_prompts=total,
        avg_score=avg_score,
        top_category=top_category,
        prompt_cards="\n".join(cards),
    )

    if output_path:
        Path(output_path).write_text(html, encoding="utf-8")
        return output_path

    return html


def export_to_gist(prompts: list[PromptData], public: bool = False) -> dict[str, Any]:
    """Export prompts to GitHub Gist using gh CLI.

    Args:
        prompts: List of prompt data dictionaries.
        public: Whether to make the gist public.

    Returns:
        Dictionary with gist URL and status.
    """
    if not prompts:
        return {"success": False, "error": "No prompts to export"}

    # Check if gh CLI is available
    try:
        result = subprocess.run(
            ["gh", "--version"],
            capture_output=True,
            text=True,
            timeout=10,
        )
        if result.returncode != 0:
            return {"success": False, "error": "gh CLI not found. Install with: brew install gh"}
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return {"success": False, "error": "gh CLI not found. Install with: brew install gh"}

    # Generate markdown content
    content = _generate_gist_markdown(prompts)

    # Create temp file
    import tempfile
    with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as f:
        f.write(content)
        temp_path = f.name

    try:
        # Create gist
        cmd = ["gh", "gist", "create", temp_path]
        if public:
            cmd.append("--public")
        cmd.extend(["--desc", "My Best Prompts - Generated by Claude-X"])

        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30,
        )

        if result.returncode == 0:
            gist_url = result.stdout.strip()
            return {
                "success": True,
                "url": gist_url,
                "public": public,
            }
        else:
            return {
                "success": False,
                "error": result.stderr or "Failed to create gist",
            }
    except subprocess.TimeoutExpired:
        return {"success": False, "error": "Timeout creating gist"}
    finally:
        # Clean up temp file
        Path(temp_path).unlink(missing_ok=True)


def export_to_json(prompts: list[PromptData], output_path: str | None = None) -> str:
    """Export prompts to JSON file.

    Args:
        prompts: List of prompt data dictionaries.
        output_path: Output file path. If None, returns JSON string.

    Returns:
        Path to generated file or JSON string.
    """
    data = {
        "generated_at": datetime.now().isoformat(),
        "total": len(prompts),
        "prompts": prompts,
    }

    json_str = json.dumps(data, ensure_ascii=False, indent=2)

    if output_path:
        Path(output_path).write_text(json_str, encoding="utf-8")
        return output_path

    return json_str


def _generate_gist_markdown(prompts: list[PromptData]) -> str:
    """Generate markdown content for Gist."""
    lines = [
        "# My Best Prompts",
        "",
        f"Generated by [Claude-X](https://github.com/kakao-lucas-ms/claude-x) on {datetime.now().strftime('%Y-%m-%d')}",
        "",
        f"**Total Prompts:** {len(prompts)}",
        "",
        "---",
        "",
    ]

    for i, prompt in enumerate(prompts, 1):
        score = _get_combined_score(prompt)
        lines.extend([
            f"## {i}. Score: {score:.1f}/10",
            "",
            f"**Category:** {prompt.get('category', 'Unknown')}",
            f"**Project:** {prompt.get('project', 'Unknown')}",
            "",
            "```",
            prompt.get("first_prompt", ""),
            "```",
            "",
            "---",
            "",
        ])

    return "\n".join(lines)


def _generate_empty_html() -> str:
    """Generate HTML for empty prompt list."""
    return HTML_TEMPLATE.format(
        generated_date=datetime.now().strftime("%Y-%m-%d %H:%M"),
        total_prompts=0,
        avg_score=0,
        top_category="N/A",
        prompt_cards="<p>No prompts found. Use Claude Code to generate some prompts first!</p>",
    )


def _get_combined_score(prompt: PromptData) -> float:
    """Get combined score from prompt data."""
    structure = prompt.get("structure_score", 0)
    context = prompt.get("context_score", 0)
    return (structure + context) / 2


def _escape_html(text: str) -> str:
    """Escape HTML special characters."""
    return (
        text
        .replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
        .replace("'", "&#x27;")
    )
