"""CSV exporter for audit history."""

import csv
import io
from pathlib import Path
from typing import Any

from tools.view_history.utils import normalize_affected_files


class CsvExporter:
    """Exports audits to CSV format with one row per finding."""

    HEADERS = [
        "audit_id",
        "audit_date",
        "audit_time",
        "lens",
        "confidence",
        "severity",
        "category",
        "description",
        "remediation",
        "affected_files",
        "cwe_id",
    ]

    def __init__(self, project_name: str, audits: list[dict[str, Any]]) -> None:
        self.project_name = project_name
        self.audits = audits

    def export(self, output_path: Path) -> None:
        """Export audits to a CSV file with UTF-8 BOM for Excel compatibility."""
        content = self.to_csv()
        output_path.write_text("\ufeff" + content, encoding="utf-8")

    def to_csv(self) -> str:
        """Convert audits to CSV string."""
        output = io.StringIO()
        writer = csv.writer(output, quoting=csv.QUOTE_MINIMAL)

        writer.writerow(self.HEADERS)

        for audit in self.audits:
            rows = self._audit_to_rows(audit)
            for row in rows:
                writer.writerow(row)

        return output.getvalue()

    def _audit_to_rows(self, audit: dict[str, Any]) -> list[list[str]]:
        """Convert a single audit to CSV rows (one per finding)."""
        audit_id = audit.get("dir_name", "")
        timestamp = audit.get("timestamp", "")
        audit_date, audit_time = self._parse_timestamp(timestamp)
        lens = audit.get("lens", "")
        confidence = audit.get("confidence", "")

        findings = audit.get("findings", [])

        if not findings:
            return [
                [
                    audit_id,
                    audit_date,
                    audit_time,
                    lens,
                    confidence,
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                ]
            ]

        rows = []
        for finding in findings:
            affected_files = normalize_affected_files(
                finding.get("affected_files", [])
            )
            rows.append(
                [
                    audit_id,
                    audit_date,
                    audit_time,
                    lens,
                    confidence,
                    finding.get("severity", ""),
                    finding.get("category", ""),
                    finding.get("description", ""),
                    finding.get("remediation", ""),
                    "|".join(affected_files),
                    finding.get("cwe_id", ""),
                ]
            )
        return rows

    def _parse_timestamp(self, timestamp: str) -> tuple[str, str]:
        """Parse timestamp into date and time components."""
        if not timestamp:
            return "", ""

        try:
            if "T" in timestamp:
                date_part, time_part = timestamp.split("T")
                time_part = time_part.split(".")[0]
                return date_part, time_part
            elif " " in timestamp:
                parts = timestamp.split(" ")
                return parts[0], parts[1] if len(parts) > 1 else ""
            return timestamp, ""
        except Exception:
            return timestamp, ""

