"""Export formatters for analytics data."""

from __future__ import annotations

import json

from cleave.core.yaml_utils import to_yaml


def export_json(analytics: dict) -> str:
    """Export analytics as JSON.

    Args:
        analytics: Analytics data dict

    Returns:
        Formatted JSON string
    """
    return json.dumps(analytics, indent=2)


def export_yaml(analytics: dict) -> str:
    """Export analytics as YAML.

    Args:
        analytics: Analytics data dict

    Returns:
        Formatted YAML string
    """
    return to_yaml(analytics)


def export_markdown(analytics: dict) -> str:
    """Export analytics as Markdown report.

    Args:
        analytics: Analytics data dict

    Returns:
        Formatted Markdown string
    """
    lines = [
        "# Performance Analytics",
        "",
        "## Summary",
        "",
        f"- **Total Operations:** {analytics['total_operations']}",
        f"- **Total Executions:** {analytics['total_executions']}",
        f"- **Total Time:** {analytics['summary']['total_time']:.4f}s",
        f"- **Average Time:** {analytics['summary']['avg_time']:.4f}s",
        "",
        "## Operations",
        "",
        "| Operation | Count | Avg Time | Total Time | Min | Max |",
        "|-----------|-------|----------|------------|-----|-----|",
    ]

    for op in analytics["operations"]:
        min_time = f"{op['min_time']:.4f}s" if op['min_time'] is not None else "N/A"
        max_time = f"{op['max_time']:.4f}s" if op['max_time'] is not None else "N/A"

        lines.append(
            f"| {op['name']} | {op['count']} | {op['avg_time']:.4f}s | "
            f"{op['total_time']:.4f}s | {min_time} | {max_time} |"
        )

    # Add memory section if any operations have memory data
    memory_ops = [op for op in analytics["operations"] if op.get("peak_memory_mb")]
    if memory_ops:
        lines.extend([
            "",
            "## Memory Usage",
            "",
            "| Operation | Count | Peak Memory | Avg Memory |",
            "|-----------|-------|-------------|------------|",
        ])

        for op in memory_ops:
            lines.append(
                f"| {op['name']} | {op['count']} | "
                f"{op['peak_memory_mb']:.2f} MB | "
                f"{op.get('avg_memory_mb', 0):.2f} MB |"
            )

    return "\n".join(lines)


def export_prometheus(analytics: dict) -> str:
    """Export analytics in Prometheus exposition format.

    Args:
        analytics: Analytics data dict

    Returns:
        Prometheus-formatted metrics string
    """
    lines = [
        "# HELP cleave_operation_count Number of times each operation was executed",
        "# TYPE cleave_operation_count counter",
    ]

    for op in analytics["operations"]:
        lines.append(f'cleave_operation_count{{operation="{op["name"]}"}} {op["count"]}')

    lines.extend([
        "",
        "# HELP cleave_operation_duration_seconds Average duration of each operation",
        "# TYPE cleave_operation_duration_seconds gauge",
    ])

    for op in analytics["operations"]:
        lines.append(
            f'cleave_operation_duration_seconds{{operation="{op["name"]}"}} {op["avg_time"]}'
        )

    lines.extend([
        "",
        "# HELP cleave_operation_duration_total_seconds Total time spent in each operation",
        "# TYPE cleave_operation_duration_total_seconds counter",
    ])

    for op in analytics["operations"]:
        lines.append(
            f'cleave_operation_duration_total_seconds{{operation="{op["name"]}"}} '
            f'{op["total_time"]}'
        )

    # Add memory metrics if available
    memory_ops = [op for op in analytics["operations"] if op.get("peak_memory_mb")]
    if memory_ops:
        lines.extend([
            "",
            "# HELP cleave_operation_memory_peak_bytes Peak memory usage for each operation",
            "# TYPE cleave_operation_memory_peak_bytes gauge",
        ])

        for op in memory_ops:
            bytes_value = op["peak_memory_mb"] * 1024 * 1024
            lines.append(
                f'cleave_operation_memory_peak_bytes{{operation="{op["name"]}"}} '
                f'{bytes_value:.0f}'
            )

    return "\n".join(lines) + "\n"
