"""generate_visual_report -- Self-contained HTML report with Chart.js.

Generates a styled, responsive HTML report that opens in the default
browser. The AI controls layout and content entirely via HTML and CSS
design-system classes; this tool provides the scaffold, chart rendering,
and print-to-PDF styles. No Python dependencies beyond the standard
library -- Chart.js loads from CDN.
"""

import json
import logging
import webbrowser
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from ..utils import state

REPORTS_FOLDER = ".visual-reports"

logger = logging.getLogger(__name__)

TOOL_DEFINITION = {
    "name": "generate_visual_report",
    "description": (
        "Generate a self-contained HTML visual report with optional Chart.js "
        "charts. The AI builds the full body HTML on the fly -- no rigid "
        "templates. Place <canvas id=\"chart-{id}\"></canvas> inside "
        ".chart-container divs and pass matching configs in the charts array. "
        "The report auto-opens in the browser and is print-to-PDF ready "
        "(Cmd/Ctrl+P).\n\n"
        "AVAILABLE CSS CLASSES (design system):\n"
        "  Layout: .grid-2 .grid-3 .grid-4 (responsive column grids)\n"
        "  Sections: .section (padded content block with styled h2)\n"
        "  KPI Cards: .kpi-row .kpi-card .kpi-value .kpi-label\n"
        "    Accents: .kpi-green .kpi-amber .kpi-red .kpi-blue\n"
        "  Tables: .data-table (styled headers, striped rows, hover)\n"
        "  Tags: .tag .tag-green .tag-amber .tag-red .tag-blue .tag-gray\n"
        "  Charts: .chart-container > <canvas id=\"chart-{id}\"> \n"
        "  Cards: .card .card-title\n"
        "  Progress: .progress-bar .progress-fill\n"
        "    Colors: .progress-green .progress-amber .progress-red\n"
        "  Text: .text-green .text-amber .text-red .text-muted\n"
        "    Size: .text-sm .text-lg .text-xl\n"
        "    Style: .font-bold .text-center .text-right\n"
        "  Spacing: .mt-1,.mt-2,.mt-3 .mb-1,.mb-2,.mb-3 .p-1,.p-2,.p-3"
    ),
    "inputSchema": {
        "type": "object",
        "properties": {
            "filename": {
                "type": "string",
                "description": (
                    "Filename for the HTML report. Saved to the "
                    ".visual-reports/ folder in the workspace. Example: "
                    "'apac-portfolio-2026-03-16.html'"
                ),
            },
            "title": {
                "type": "string",
                "description": "Report title (header + browser tab).",
            },
            "content_html": {
                "type": "string",
                "description": (
                    "Full HTML body content built by the AI using the CSS "
                    "design system. Place <canvas id=\"chart-{id}\"> "
                    "elements where you want charts."
                ),
            },
            "charts": {
                "type": "array",
                "description": (
                    "Optional chart configurations. Each needs an id "
                    "matching a <canvas id=\"chart-{id}\"> in content_html."
                ),
                "items": {
                    "type": "object",
                    "properties": {
                        "id": {
                            "type": "string",
                            "description": (
                                "Matches the canvas element id. If the "
                                "canvas is id=\"chart-health\", pass "
                                "id=\"health\"."
                            ),
                        },
                        "type": {
                            "type": "string",
                            "description": (
                                "Chart.js type: bar, horizontalBar, "
                                "doughnut, pie, line, radar, polarArea."
                            ),
                        },
                        "title": {
                            "type": "string",
                            "description": "Chart title (displayed above).",
                        },
                        "labels": {
                            "type": "array",
                            "items": {"type": "string"},
                        },
                        "datasets": {
                            "type": "array",
                            "description": (
                                "Multiple data series. For single-series, "
                                "use values+colors shorthand instead."
                            ),
                            "items": {
                                "type": "object",
                                "properties": {
                                    "label": {"type": "string"},
                                    "values": {
                                        "type": "array",
                                        "items": {"type": "number"},
                                    },
                                    "colors": {
                                        "type": "array",
                                        "items": {"type": "string"},
                                    },
                                },
                            },
                        },
                        "values": {
                            "type": "array",
                            "items": {"type": "number"},
                            "description": "Single-series shorthand.",
                        },
                        "colors": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Single-series colors.",
                        },
                    },
                    "required": ["id", "type", "labels"],
                },
            },
            "auto_open": {
                "type": "boolean",
                "description": "Open in browser after saving (default true).",
            },
            "working_directory": {
                "type": "string",
                "description": "Workspace dir (AI passes automatically).",
            },
        },
        "required": ["filename", "title", "content_html"],
    },
}

# ---------------------------------------------------------------------------
# CSS design system
# ---------------------------------------------------------------------------

_CSS = """\
:root {
    --cs-primary: #1e40af;
    --cs-primary-light: #dbeafe;
    --cs-green: #059669;
    --cs-green-light: #d1fae5;
    --cs-amber: #d97706;
    --cs-amber-light: #fef3c7;
    --cs-red: #dc2626;
    --cs-red-light: #fee2e2;
    --cs-blue: #3b82f6;
    --cs-blue-light: #dbeafe;
    --cs-gray: #6b7280;
    --cs-gray-light: #f3f4f6;
    --cs-text: #1f2937;
    --cs-text-muted: #6b7280;
    --cs-border: #e5e7eb;
    --cs-bg: #ffffff;
    --cs-radius: 8px;
    --cs-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
                 'Helvetica Neue', Arial, sans-serif;
    color: var(--cs-text);
    background: #f8fafc;
    line-height: 1.6;
}

/* --- Header & Footer --- */
.report-header {
    background: linear-gradient(135deg, var(--cs-primary), #1e3a8a);
    color: white;
    padding: 2rem 2.5rem;
    margin-bottom: 1.5rem;
}
.report-header h1 { font-size: 1.75rem; font-weight: 700; margin-bottom: 0.25rem; }
.report-header-row {
    display: flex; justify-content: space-between; align-items: flex-start;
}
.report-meta { opacity: 0.8; font-size: 0.875rem; }
.print-btn {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.4);
    padding: 0.5rem 1.25rem;
    border-radius: var(--cs-radius);
    font-size: 0.875rem;
    font-weight: 600;
    cursor: pointer;
    white-space: nowrap;
    transition: background 0.2s;
}
.print-btn:hover { background: rgba(255,255,255,0.35); }
.report-footer {
    text-align: center;
    padding: 1.5rem;
    color: var(--cs-text-muted);
    font-size: 0.75rem;
    border-top: 1px solid var(--cs-border);
    margin-top: 2rem;
}

/* --- Main --- */
main { max-width: 1200px; margin: 0 auto; padding: 0 1.5rem 2rem; }

/* --- Section --- */
.section { margin-bottom: 1.5rem; }
.section h2, .section-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--cs-primary);
    margin-bottom: 0.75rem;
    padding-bottom: 0.5rem;
    border-bottom: 2px solid var(--cs-primary-light);
}

/* --- Grid --- */
.grid-2 { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; }
.grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; }
.grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; }

/* --- KPI Cards --- */
.kpi-row {
    display: flex; flex-wrap: wrap; gap: 1rem; margin-bottom: 1.5rem;
}
.kpi-card {
    flex: 1; min-width: 140px;
    background: var(--cs-bg);
    border-radius: var(--cs-radius);
    padding: 1.25rem;
    text-align: center;
    box-shadow: var(--cs-shadow);
    border-top: 4px solid var(--cs-border);
}
.kpi-value { font-size: 2rem; font-weight: 700; line-height: 1.2; }
.kpi-label {
    font-size: 0.8rem; color: var(--cs-text-muted); margin-top: 0.25rem;
    text-transform: uppercase; letter-spacing: 0.05em;
}
.kpi-green  { border-top-color: var(--cs-green); }
.kpi-green  .kpi-value { color: var(--cs-green); }
.kpi-amber  { border-top-color: var(--cs-amber); }
.kpi-amber  .kpi-value { color: var(--cs-amber); }
.kpi-red    { border-top-color: var(--cs-red); }
.kpi-red    .kpi-value { color: var(--cs-red); }
.kpi-blue   { border-top-color: var(--cs-blue); }
.kpi-blue   .kpi-value { color: var(--cs-blue); }

/* --- Data Table --- */
.data-table {
    width: 100%; border-collapse: collapse;
    background: var(--cs-bg);
    border-radius: var(--cs-radius);
    overflow: hidden;
    box-shadow: var(--cs-shadow);
    font-size: 0.875rem;
}
.data-table th {
    background: var(--cs-primary); color: white;
    padding: 0.75rem 1rem; text-align: left;
    font-weight: 600; font-size: 0.8rem;
    text-transform: uppercase; letter-spacing: 0.03em;
}
.data-table td {
    padding: 0.625rem 1rem;
    border-bottom: 1px solid var(--cs-border);
}
.data-table tr:nth-child(even) td { background: #f9fafb; }
.data-table tr:hover td { background: var(--cs-primary-light); }

/* --- Tags / Badges --- */
.tag {
    display: inline-block; padding: 0.15rem 0.5rem;
    border-radius: 9999px; font-size: 0.7rem;
    font-weight: 600; text-transform: uppercase;
    letter-spacing: 0.03em;
}
.tag-green { background: var(--cs-green-light); color: var(--cs-green); }
.tag-amber { background: var(--cs-amber-light); color: var(--cs-amber); }
.tag-red   { background: var(--cs-red-light);   color: var(--cs-red); }
.tag-blue  { background: var(--cs-blue-light);  color: var(--cs-blue); }
.tag-gray  { background: var(--cs-gray-light);  color: var(--cs-gray); }

/* --- Chart Container --- */
.chart-container {
    background: var(--cs-bg);
    border-radius: var(--cs-radius);
    padding: 1rem;
    box-shadow: var(--cs-shadow);
    margin-bottom: 1rem;
    position: relative;
    max-height: 400px;
}
.chart-container canvas { max-height: 350px; }

/* --- Cards --- */
.card {
    background: var(--cs-bg);
    border-radius: var(--cs-radius);
    padding: 1.25rem;
    box-shadow: var(--cs-shadow);
    border: 1px solid var(--cs-border);
    margin-bottom: 1rem;
}
.card-title { font-size: 1rem; font-weight: 600; margin-bottom: 0.5rem; }

/* --- Progress Bar --- */
.progress-bar {
    width: 100%; height: 8px;
    background: var(--cs-gray-light);
    border-radius: 4px; overflow: hidden;
}
.progress-fill {
    height: 100%; border-radius: 4px;
    transition: width 0.3s ease;
}
.progress-green .progress-fill,
.progress-fill.progress-green { background: var(--cs-green); }
.progress-amber .progress-fill,
.progress-fill.progress-amber { background: var(--cs-amber); }
.progress-red .progress-fill,
.progress-fill.progress-red   { background: var(--cs-red); }

/* --- Text utilities --- */
.text-green  { color: var(--cs-green) !important; }
.text-amber  { color: var(--cs-amber) !important; }
.text-red    { color: var(--cs-red) !important; }
.text-blue   { color: var(--cs-blue) !important; }
.text-muted  { color: var(--cs-text-muted) !important; }
.text-sm     { font-size: 0.875rem; }
.text-lg     { font-size: 1.125rem; }
.text-xl     { font-size: 1.5rem; }
.font-bold   { font-weight: 700; }
.text-center { text-align: center; }
.text-right  { text-align: right; }

/* --- Spacing --- */
.mt-1 { margin-top: 0.5rem; }   .mb-1 { margin-bottom: 0.5rem; }
.mt-2 { margin-top: 1rem; }     .mb-2 { margin-bottom: 1rem; }
.mt-3 { margin-top: 1.5rem; }   .mb-3 { margin-bottom: 1.5rem; }
.p-1  { padding: 0.5rem; }
.p-2  { padding: 1rem; }
.p-3  { padding: 1.5rem; }

/* --- Responsive --- */
@media (max-width: 768px) {
    .grid-2, .grid-3, .grid-4 { grid-template-columns: 1fr; }
    .kpi-row { flex-direction: column; }
    main { padding: 0 1rem 1.5rem; }
    .report-header { padding: 1.5rem; }
}

/* --- Print --- */
@media print {
    body {
        background: white;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    .report-header { break-after: avoid; }
    .section { break-inside: avoid; }
    .kpi-row { break-inside: avoid; }
    .data-table { break-inside: auto; }
    .data-table tr { break-inside: avoid; }
    .chart-container { break-inside: avoid; }
    .card { break-inside: avoid; }
    .report-footer { break-before: avoid; }
    main { max-width: 100%; padding: 0; }
    .chart-container { box-shadow: none; border: 1px solid #ddd; }
    .kpi-card { box-shadow: none; border: 1px solid #ddd; }
    .card { box-shadow: none; }
    .data-table { box-shadow: none; border: 1px solid #ddd; }
    .chart-print-img { width: 100%; height: auto; }
    .chart-print-img + canvas { display: none; }
    .print-btn { display: none; }
}
"""

# ---------------------------------------------------------------------------
# Chart.js initialization + print handler
# ---------------------------------------------------------------------------

_CHART_SCRIPT = """\
(function() {
    var DEFAULT_COLORS = [
        '#3b82f6','#059669','#d97706','#dc2626','#8b5cf6',
        '#06b6d4','#ec4899','#f97316','#14b8a6','#6366f1',
        '#a855f7','#0ea5e9','#84cc16','#f43f5e','#facc15'
    ];

    var configs = window.__CHART_CONFIGS__ || [];
    configs.forEach(function(cfg) {
        var canvas = document.getElementById('chart-' + cfg.id);
        if (!canvas) return;

        var isHorizontal = cfg.type === 'horizontalBar';
        var chartType = isHorizontal ? 'bar' : cfg.type;
        var isPie = ['doughnut','pie','polarArea'].indexOf(chartType) >= 0;
        var datasets;

        if (cfg.datasets && cfg.datasets.length) {
            datasets = cfg.datasets.map(function(ds, i) {
                var c = ds.colors || DEFAULT_COLORS;
                return {
                    label: ds.label || '',
                    data: ds.values || [],
                    backgroundColor: isPie ? c : (c[i % c.length] || c),
                    borderColor: isPie ? '#fff' : (c[i % c.length] || c[0]),
                    borderWidth: isPie ? 2 : 1
                };
            });
        } else {
            var c = cfg.colors || DEFAULT_COLORS;
            datasets = [{
                label: cfg.title || '',
                data: cfg.values || [],
                backgroundColor: c,
                borderColor: isPie ? '#fff' : c,
                borderWidth: isPie ? 2 : 1
            }];
        }

        var options = {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                title: {
                    display: !!cfg.title,
                    text: cfg.title || '',
                    font: { size: 14, weight: '600' },
                    color: '#1f2937'
                },
                legend: {
                    display: isPie || chartType === 'radar',
                    position: 'bottom',
                    labels: { padding: 12, usePointStyle: true }
                }
            }
        };

        if (isHorizontal) options.indexAxis = 'y';

        if (chartType === 'bar' || chartType === 'line') {
            var xAxis = { grid: { display: false } };
            var yAxis = { beginAtZero: true, grid: { color: '#f3f4f6' } };
            if (isHorizontal) {
                options.scales = { x: yAxis, y: xAxis };
            } else {
                options.scales = { x: xAxis, y: yAxis };
            }
        }

        new Chart(canvas, {
            type: chartType,
            data: { labels: cfg.labels, datasets: datasets },
            options: options
        });
    });

    /* Convert canvases to static images for reliable print / PDF */
    window.addEventListener('beforeprint', function() {
        document.querySelectorAll('.chart-container canvas').forEach(function(cv) {
            if (cv.previousElementSibling &&
                cv.previousElementSibling.classList.contains('chart-print-img')) return;
            try {
                var img = new Image();
                img.src = cv.toDataURL('image/png');
                img.className = 'chart-print-img';
                cv.parentNode.insertBefore(img, cv);
            } catch(e) {}
        });
    });
    window.addEventListener('afterprint', function() {
        document.querySelectorAll('.chart-print-img').forEach(function(i) {
            i.remove();
        });
    });
})();
"""


def _build_html(
    title: str,
    content_html: str,
    charts: list[dict],
    generated_at: str,
) -> str:
    """Assemble the complete self-contained HTML document."""
    charts_json = json.dumps(charts, indent=2) if charts else "[]"

    return (
        "<!DOCTYPE html>\n"
        '<html lang="en">\n'
        "<head>\n"
        '    <meta charset="UTF-8">\n'
        '    <meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
        f"    <title>{title}</title>\n"
        '    <script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>\n'
        f"    <style>\n{_CSS}\n    </style>\n"
        "</head>\n"
        "<body>\n"
        '    <header class="report-header">\n'
        '        <div class="report-header-row">\n'
        "            <div>\n"
        f"                <h1>{title}</h1>\n"
        f'                <p class="report-meta">Generated {generated_at} &middot; '
        "CloudSense Customer Compass</p>\n"
        "            </div>\n"
        '            <button class="print-btn" onclick="window.print()">'
        "\U0001f5a8\ufe0f Save as PDF</button>\n"
        "        </div>\n"
        "    </header>\n"
        "    <main>\n"
        f"{content_html}\n"
        "    </main>\n"
        '    <footer class="report-footer">\n'
        f"        CloudSense Customer Compass &middot; Generated {generated_at}\n"
        "    </footer>\n"
        "    <script>\n"
        f"        window.__CHART_CONFIGS__ = {charts_json};\n"
        f"        {_CHART_SCRIPT}\n"
        "    </script>\n"
        "</body>\n"
        "</html>"
    )


async def run(arguments: dict[str, Any]) -> str:
    """Execute the generate_visual_report tool."""
    state.set_working_dir(arguments.get("working_directory"))
    working_dir = state.get_working_dir()

    filename = arguments.get("filename", "")
    title = arguments.get("title", "")
    content_html = arguments.get("content_html", "")
    charts = arguments.get("charts") or []
    auto_open = arguments.get("auto_open", True)

    if not filename:
        return "STATUS: ERROR\n\nfilename is required."
    if not title:
        return "STATUS: ERROR\n\ntitle is required."
    if not content_html:
        return "STATUS: ERROR\n\ncontent_html is required."

    basename = Path(filename).name
    if not basename:
        return "STATUS: ERROR\n\nfilename must be a valid file name."

    if not basename.endswith(".html"):
        basename += ".html"

    reports_dir = working_dir / REPORTS_FOLDER
    reports_dir.mkdir(parents=True, exist_ok=True)
    out_path = reports_dir / basename

    generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    html = _build_html(title, content_html, charts, generated_at)

    out_path.write_text(html, encoding="utf-8")

    size_kb = out_path.stat().st_size / 1024

    if auto_open:
        try:
            webbrowser.open(out_path.as_uri())
            opened = "Opened in default browser."
        except Exception:
            opened = "Could not auto-open browser."
    else:
        opened = "auto_open=false; not opened."

    return (
        f"STATUS: SAVED\n\n"
        f"Visual report written to `{out_path}` ({size_kb:.1f} KB).\n"
        f"{opened}\n\n"
        f"The user can print to PDF from the browser (Cmd/Ctrl+P) or "
        f"use the Save as PDF button in the report header.\n"
        f"The markdown report (saved via save_report) is the permanent "
        f"artifact."
    )
