"""JSON/CSV/console output formatters."""

from __future__ import annotations

import csv
import io
import json
import re
from pathlib import Path


def _sanitize_filename(name: str) -> str:
    """Convert a database name to a safe filename component."""
    return re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")


def format_json(results: dict) -> str:
    """Format results as a JSON string."""
    return json.dumps(results, indent=2, default=str)


def format_csv(results: dict) -> str:
    """Format results as CSV string."""
    output = io.StringIO(newline="")
    writer = csv.writer(output, lineterminator="\n")
    writer.writerow(["element", "type", "result", "error", "duration_ms"])
    for r in results["results"]:
        writer.writerow([
            r["element"],
            r["type"],
            r["result"],
            r.get("error", ""),
            r["duration_ms"],
        ])
    return output.getvalue()


def format_console(results: dict) -> str:
    """Format results as human-readable console output."""
    meta = results["metadata"]
    lines = [
        f"Results: {meta['passed']} passed, {meta['failed']} failed ({meta['pass_rate']})",
        "",
        "Summary by type:",
    ]
    for type_name, summary in results["summary_by_type"].items():
        lines.append(
            f"  {type_name}: {summary['passed']}/{summary['total']} passed"
        )
    return "\n".join(lines)


def write_output(
    results: dict,
    output_dir: str | Path = "./results",
    format: str = "both",
) -> list[str]:
    """Write results to files.

    Args:
        results: Full results dict.
        output_dir: Directory to write files to.
        format: One of "json", "csv", or "both".

    Returns:
        List of written file paths.
    """
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    db_name = _sanitize_filename(results["metadata"].get("database", "unknown"))
    timestamp = results["metadata"].get("timestamp", "")[:10]  # YYYY-MM-DD
    base = f"{db_name}_{timestamp}"

    written = []

    if format in ("json", "both"):
        json_path = output_path / f"{base}.json"
        json_path.write_text(format_json(results))
        written.append(str(json_path))

    if format in ("csv", "both"):
        csv_path = output_path / f"{base}.csv"
        csv_path.write_text(format_csv(results))
        written.append(str(csv_path))

    return written
