#!/usr/bin/env python3
# /// script
# dependencies = [
#     "psutil>=5.9.0",
#     "click>=8.1.0",
#     "rich>=13.0.0",
#     "jinja2>=3.0.0",
# ]
# ///

"""
macOS Resource Optimizer - System Analysis Report Generator

Generates comprehensive system analysis reports in multiple formats.

Features:
- Multiple output formats (Markdown, JSON, HTML)
- Executive summary with overall health
- Category breakdown with recommendations
- Critical issues priority list
- Performance metrics
- Embedded Jinja2 templates

Usage:
    # Generate Markdown report (default)
    uv run report.py

    # Generate HTML report and save to file
    uv run report.py --format html --output report.html

    # Generate JSON report
    uv run report.py --format json --output report.json

Exit Codes:
    0: Success
    3: Report generation error
"""

import asyncio
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

import click
from jinja2 import Template
from rich.console import Console


class ReportGenerator:
    """Embedded report generation engine with multiple format support."""

    # Jinja2 template for Markdown reports
    MARKDOWN_TEMPLATE = """
# macOS Resource Optimizer - System Analysis Report

**Generated**: {{ timestamp }}
**Overall Status**: {{ overall_status }}
**Risk Level**: {{ overall_risk }}
**Total Categories**: {{ total_categories }}

---

## Executive Summary

{{ summary }}

---

## Category Analysis

{% for category, data in categories.items() %}
### {{ category.upper() }}

- **Status**: {{ data.analysis.status }}
- **Risk Level**: {{ data.analysis.risk_level }}
- **Recommendations**: {{ data.analysis.recommendations|length }}

{% if data.analysis.recommendations %}
**Actionable Recommendations**:
{% for rec in data.analysis.recommendations[:3] %}
- {{ rec.action or rec.issue or rec.description or "Review and optimize" }}
{% endfor %}
{% if data.analysis.recommendations|length > 3 %}
- *...and {{ data.analysis.recommendations|length - 3 }} more recommendations*
{% endif %}
{% endif %}

{% endfor %}

---

## Critical Issues

{% if critical_issues %}
{% for issue in critical_issues %}
{{ loop.index }}. {{ issue }}
{% endfor %}
{% else %}
*No critical issues detected.*
{% endif %}

---

## Performance Metrics

- **Total Analysis Time**: {{ performance.execution_time_ms }}ms
- **Categories Analyzed**: {{ performance.categories_analyzed }}
- **Recommendations Generated**: {{ performance.total_recommendations }}
- **Critical Issues Found**: {{ performance.critical_issues_count }}

---

*Report generated by macOS Resource Optimizer*
*For more details, run individual analyzers or use `analyze_all.py`*
"""

    # Jinja2 template for HTML reports
    HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>macOS Resource Optimizer Report - {{ timestamp }}</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            line-height: 1.6;
            color: #333;
            background: #f5f5f7;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 40px;
        }

        h1 {
            color: #1d1d1f;
            margin-bottom: 10px;
            font-size: 2.5em;
        }

        h2 {
            color: #1d1d1f;
            margin-top: 30px;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #e5e5e7;
        }

        h3 {
            color: #424245;
            margin-top: 20px;
            margin-bottom: 10px;
        }

        .metadata {
            display: flex;
            gap: 30px;
            margin-bottom: 30px;
            padding: 20px;
            background: #f5f5f7;
            border-radius: 8px;
        }

        .metadata-item {
            display: flex;
            flex-direction: column;
        }

        .metadata-label {
            font-size: 0.85em;
            color: #86868b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .metadata-value {
            font-size: 1.2em;
            font-weight: 600;
            margin-top: 5px;
        }

        .status-healthy { color: #34c759; }
        .status-warning { color: #ff9500; }
        .status-critical { color: #ff3b30; }

        .risk-low { color: #34c759; }
        .risk-medium { color: #ff9500; }
        .risk-high { color: #ff9500; }
        .risk-critical { color: #ff3b30; }

        .summary {
            background: #f5f5f7;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            font-size: 1.1em;
            line-height: 1.8;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e5e5e7;
        }

        th {
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85em;
            letter-spacing: 0.5px;
        }

        tbody tr:hover {
            background: #f5f5f7;
        }

        .category-card {
            background: white;
            border: 1px solid #e5e5e7;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .category-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .category-title {
            font-size: 1.3em;
            font-weight: 600;
        }

        .badge {
            padding: 5px 12px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .badge-low { background: #d1f2dd; color: #248a3d; }
        .badge-medium { background: #ffe5cc; color: #c93; }
        .badge-high { background: #ffe5cc; color: #c93; }
        .badge-critical { background: #ffd4d1; color: #d70015; }

        ul {
            margin: 15px 0;
            padding-left: 25px;
        }

        li {
            margin: 8px 0;
            line-height: 1.6;
        }

        .issue-list {
            background: #fff5f5;
            border-left: 4px solid #ff3b30;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }

        .issue-list li {
            margin: 12px 0;
        }

        .metrics {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }

        .metric-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            text-align: center;
        }

        .metric-value {
            font-size: 2.5em;
            font-weight: 700;
            margin: 10px 0;
        }

        .metric-label {
            font-size: 0.9em;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e5e5e7;
            text-align: center;
            color: #86868b;
            font-size: 0.9em;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>macOS Resource Optimizer</h1>
        <p style="color: #86868b; font-size: 1.1em; margin-bottom: 30px;">System Analysis Report</p>

        <div class="metadata">
            <div class="metadata-item">
                <span class="metadata-label">Generated</span>
                <span class="metadata-value">{{ timestamp }}</span>
            </div>
            <div class="metadata-item">
                <span class="metadata-label">Overall Status</span>
                <span class="metadata-value status-{{ overall_status }}">{{ overall_status.upper() }}</span>
            </div>
            <div class="metadata-item">
                <span class="metadata-label">Risk Level</span>
                <span class="metadata-value risk-{{ overall_risk }}">{{ overall_risk.upper() }}</span>
            </div>
            <div class="metadata-item">
                <span class="metadata-label">Categories</span>
                <span class="metadata-value">{{ total_categories }}</span>
            </div>
        </div>

        <h2>Executive Summary</h2>
        <div class="summary">
            {{ summary }}
        </div>

        <h2>Category Analysis</h2>
        <table>
            <thead>
                <tr>
                    <th>Category</th>
                    <th>Status</th>
                    <th>Risk Level</th>
                    <th>Recommendations</th>
                </tr>
            </thead>
            <tbody>
                {% for category, data in categories.items() %}
                <tr>
                    <td><strong>{{ category.upper() }}</strong></td>
                    <td class="status-{{ data.analysis.status }}">{{ data.analysis.status }}</td>
                    <td><span class="badge badge-{{ data.analysis.risk_level }}">{{ data.analysis.risk_level }}</span></td>
                    <td>{{ data.analysis.recommendations|length }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>

        <h2>Detailed Recommendations</h2>
        {% for category, data in categories.items() %}
        {% if data.analysis.recommendations %}
        <div class="category-card">
            <div class="category-header">
                <span class="category-title">{{ category.upper() }}</span>
                <span class="badge badge-{{ data.analysis.risk_level }}">{{ data.analysis.risk_level }}</span>
            </div>
            <ul>
                {% for rec in data.analysis.recommendations %}
                <li>{{ rec.action or rec.issue or rec.description or "Review and optimize" }}</li>
                {% endfor %}
            </ul>
        </div>
        {% endif %}
        {% endfor %}

        <h2>Critical Issues</h2>
        {% if critical_issues %}
        <div class="issue-list">
            <ul>
                {% for issue in critical_issues %}
                <li><strong>{{ issue }}</strong></li>
                {% endfor %}
            </ul>
        </div>
        {% else %}
        <p style="color: #34c759; font-weight: 600;">✅ No critical issues detected.</p>
        {% endif %}

        <h2>Performance Metrics</h2>
        <div class="metrics">
            <div class="metric-card">
                <div class="metric-label">Analysis Time</div>
                <div class="metric-value">{{ performance.execution_time_ms }}ms</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">Categories Analyzed</div>
                <div class="metric-value">{{ performance.categories_analyzed }}</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">Recommendations</div>
                <div class="metric-value">{{ performance.total_recommendations }}</div>
            </div>
            <div class="metric-card">
                <div class="metric-label">Critical Issues</div>
                <div class="metric-value">{{ performance.critical_issues_count }}</div>
            </div>
        </div>

        <footer>
            <p>Generated by macOS Resource Optimizer</p>
            <p>For more details, run individual analyzers or use <code>analyze_all.py</code></p>
        </footer>
    </div>
</body>
</html>
"""

    def __init__(self):
        """Initialize report generator."""
        self.console = Console()

    async def collect_data(self) -> Dict[str, Any]:
        """
        Run analyze_all.py to collect current system data.

        Returns:
            Analysis results as dictionary

        Raises:
            Exception: If data collection fails
        """
        analyze_script = Path(__file__).parent / "analyze_all.py"

        proc = await asyncio.create_subprocess_exec(
            "uv",
            "run",
            str(analyze_script),
            "--json",
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )

        stdout, stderr = await proc.communicate()

        if proc.returncode in [0, 1, 2]:
            return json.loads(stdout.decode())
        else:
            raise Exception(f"Data collection failed: {stderr.decode()}")

    def generate_markdown(self, data: Dict[str, Any]) -> str:
        """
        Generate Markdown format report.

        Args:
            data: Analysis data from analyze_all.py

        Returns:
            Formatted Markdown report as string
        """
        template = Template(self.MARKDOWN_TEMPLATE)

        return template.render(
            timestamp=datetime.now().isoformat(),
            overall_status=data["overall"]["status"],
            overall_risk=data["overall"]["risk_level"],
            total_categories=len(data["categories"]),
            summary=self._generate_summary(data),
            categories=data["categories"],
            critical_issues=self._extract_critical_issues(data),
            performance=self._extract_performance_metrics(data),
        )

    def generate_html(self, data: Dict[str, Any]) -> str:
        """
        Generate HTML format report.

        Args:
            data: Analysis data from analyze_all.py

        Returns:
            Formatted HTML report as string
        """
        template = Template(self.HTML_TEMPLATE)

        return template.render(
            timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            overall_status=data["overall"]["status"],
            overall_risk=data["overall"]["risk_level"],
            total_categories=len(data["categories"]),
            summary=self._generate_summary(data),
            categories=data["categories"],
            critical_issues=self._extract_critical_issues(data),
            performance=self._extract_performance_metrics(data),
        )

    def generate_json(self, data: Dict[str, Any]) -> str:
        """
        Generate JSON format report.

        Args:
            data: Analysis data from analyze_all.py

        Returns:
            Pretty-printed JSON report as string
        """
        report = {
            "metadata": {
                "generated": datetime.now().isoformat(),
                "generator": "macOS Resource Optimizer",
                "version": "1.0.0",
            },
            "overall": data["overall"],
            "summary": self._generate_summary(data),
            "categories": data["categories"],
            "critical_issues": self._extract_critical_issues(data),
            "performance": self._extract_performance_metrics(data),
        }

        return json.dumps(report, indent=2)

    def _generate_summary(self, data: Dict[str, Any]) -> str:
        """
        Generate executive summary text.

        Args:
            data: Analysis data

        Returns:
            Summary text
        """
        overall = data["overall"]
        categories = data["categories"]

        total_recommendations = sum(
            len(cat.get("analysis", {}).get("recommendations", []))
            for cat in categories.values()
        )

        critical_count = len(self._extract_critical_issues(data))

        return (
            f"System analysis completed with {overall['status']} overall status and "
            f"{overall['risk_level']} risk level. Analyzed {len(categories)} resource categories "
            f"and generated {total_recommendations} actionable recommendations. "
            f"{critical_count} critical issues require immediate attention."
        )

    def _extract_critical_issues(self, data: Dict[str, Any]) -> List[str]:
        """
        Extract critical issues from analysis.

        Args:
            data: Analysis data

        Returns:
            List of critical issue descriptions
        """
        issues = []

        for category, cat_data in data["categories"].items():
            analysis = cat_data.get("analysis", {})
            if analysis.get("risk_level") in ["high", "critical"]:
                for rec in analysis.get("recommendations", []):
                    issue_text = (
                        rec.get("action")
                        or rec.get("issue")
                        or rec.get("description")
                        or str(rec)
                    )
                    issues.append(f"{category.upper()}: {issue_text}")

        return issues

    def _extract_performance_metrics(self, data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Extract performance metrics from analysis.

        Args:
            data: Analysis data

        Returns:
            Performance metrics dictionary
        """
        categories = data["categories"]

        total_recommendations = sum(
            len(cat.get("analysis", {}).get("recommendations", []))
            for cat in categories.values()
        )

        return {
            "execution_time_ms": data.get("execution_time_ms", 0),
            "categories_analyzed": len(categories),
            "total_recommendations": total_recommendations,
            "critical_issues_count": len(self._extract_critical_issues(data)),
        }


@click.command()
@click.option(
    "--format",
    type=click.Choice(["markdown", "json", "html"], case_sensitive=False),
    default="markdown",
    help="Report format (default: markdown)",
)
@click.option("--output", type=click.Path(), help="Output file path (default: stdout)")
def main(format: str, output: Optional[str]) -> None:
    """
    Generate comprehensive system analysis report.

    Runs system analysis and generates reports in multiple formats (Markdown, JSON, HTML).

    Examples:

        # Generate Markdown report (default)
        uv run report.py

        # Generate HTML report and save to file
        uv run report.py --format html --output report.html

        # Generate JSON report
        uv run report.py --format json --output report.json

        # Print HTML to stdout
        uv run report.py --format html
    """
    try:
        generator = ReportGenerator()

        # Collect data
        generator.console.print("[cyan]Collecting system data...[/cyan]")
        data = asyncio.run(generator.collect_data())

        # Generate report in requested format
        if format == "markdown":
            content = generator.generate_markdown(data)
        elif format == "json":
            content = generator.generate_json(data)
        elif format == "html":
            content = generator.generate_html(data)

        # Output to file or stdout
        if output:
            Path(output).write_text(content)
            click.echo(f"✅ Report saved to: {output}")
        else:
            click.echo(content)

        sys.exit(0)

    except Exception as e:
        click.echo(f"❌ Report generation error: {e}", err=True)
        sys.exit(3)


if __name__ == "__main__":
    main()
