"""Data export tools."""

import csv
import io
import json

from pydantic_ai.toolsets import FunctionToolset

export_toolset: FunctionToolset[None] = FunctionToolset()


@export_toolset.tool
def export_to_csv(
    data: list[dict[str, str | int | float]],
    columns: list[str] | None = None,
) -> str:
    """Export data to CSV format.

    Args:
        data: List of dictionaries to export.
        columns: Optional list of column names to include (default: all).
    """
    if not data:
        return "Error: No data to export."

    # Determine columns
    if columns is None:
        columns = list(data[0].keys())

    # Create CSV
    output = io.StringIO()
    writer = csv.DictWriter(output, fieldnames=columns, extrasaction="ignore")
    writer.writeheader()
    writer.writerows(data)

    return output.getvalue()


@export_toolset.tool
def export_to_json(
    data: list[dict[str, str | int | float]] | dict[str, str | int | float],
    pretty: bool = True,
) -> str:
    """Export data to JSON format.

    Args:
        data: Data to export (dict or list of dicts).
        pretty: Whether to format with indentation.
    """
    indent = 2 if pretty else None
    return json.dumps(data, indent=indent, default=str)


@export_toolset.tool
def export_to_markdown_table(
    data: list[dict[str, str | int | float]],
    columns: list[str] | None = None,
) -> str:
    """Export data to a Markdown table.

    Args:
        data: List of dictionaries to export.
        columns: Optional list of column names to include (default: all).
    """
    if not data:
        return "Error: No data to export."

    # Determine columns
    if columns is None:
        columns = list(data[0].keys())

    # Calculate column widths
    widths = {col: len(col) for col in columns}
    for row in data:
        for col in columns:
            val = str(row.get(col, ""))
            widths[col] = max(widths[col], len(val))

    # Build table
    lines = []

    # Header
    header = " | ".join(col.ljust(widths[col]) for col in columns)
    lines.append(f"| {header} |")

    # Separator
    separator = " | ".join("-" * widths[col] for col in columns)
    lines.append(f"| {separator} |")

    # Rows
    for row in data:
        cells = []
        for col in columns:
            val = str(row.get(col, ""))
            cells.append(val.ljust(widths[col]))
        lines.append(f"| {' | '.join(cells)} |")

    return "\n".join(lines)


@export_toolset.tool
def format_as_summary(
    title: str,
    sections: dict[str, str],
) -> str:
    """Format data as a readable summary document.

    Args:
        title: Title of the summary.
        sections: Dictionary of section names to content.
    """
    lines = [f"# {title}", ""]

    for section_name, content in sections.items():
        lines.append(f"## {section_name}")
        lines.append("")
        lines.append(content)
        lines.append("")

    return "\n".join(lines)
