"""
CSV parser — entire file as a single table:simple element.

The whole CSV is one atomic table record. Header detection is automatic
(first row treated as header by default).
"""

from __future__ import annotations

import csv
import io
from collections.abc import Iterator

from .base import BaseParser, FileRecord, RawElement


def _build_markdown(headers: list[str], rows: list[list[str]]) -> str:
    """Build GFM markdown table from headers and rows."""
    lines: list[str] = []
    if headers:
        lines.append("| " + " | ".join(headers) + " |")
        lines.append("|" + "|".join("---" for _ in headers) + "|")
    for row in rows:
        # Pad short rows to header width
        padded = list(row) + [""] * max(0, len(headers) - len(row))
        lines.append("| " + " | ".join(str(c) for c in padded) + " |")
    return "\n".join(lines)


class CSVParser(BaseParser):
    handles = [("text/csv", None)]

    def parse(self, file_record: FileRecord) -> Iterator[RawElement]:
        try:
            from charset_normalizer import from_path

            result = from_path(str(file_record.path)).best()
            text = (
                str(result)
                if result
                else file_record.path.read_text(encoding="utf-8", errors="replace")
            )
        except Exception:
            text = file_record.path.read_text(encoding="utf-8", errors="replace")

        reader = csv.reader(io.StringIO(text))
        all_rows = list(reader)

        if not all_rows:
            return

        # Emit document title so the table has a section context
        yield RawElement(
            element_type="meta:document_title",
            text=file_record.path.stem,
            extra={"extraction_method": "csv:stdlib", "confidence": 1.0},
        )

        headers = all_rows[0]
        data_rows = all_rows[1:]

        markdown = _build_markdown(headers, data_rows)

        yield RawElement(
            element_type="table:simple",
            text=markdown,
            table_data={
                "markdown": markdown,
                "structured": {"headers": headers, "rows": data_rows},
                "has_header_row": True,
                "row_count": len(data_rows),
                "header_row_count": 1,
                "col_count": len(headers),
            },
            extra={
                "extraction_method": "csv:stdlib",
                "confidence": 1.0,
            },
        )
