"""Output formatting utilities for CLI."""
from __future__ import annotations

import json
from dataclasses import asdict, is_dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Any

import yaml  # type: ignore[import-untyped]

if TYPE_CHECKING:
    pass


def normalize_result(value: Any) -> Any:
    """Normalize result for JSON/YAML serialization.
    
    Args:
        value: Value to normalize
        
    Returns:
        Normalized value suitable for serialization
    """
    if is_dataclass(value) and not isinstance(value, type):
        return {key: normalize_result(item) for key, item in asdict(value).items()}
    if isinstance(value, Path):
        return str(value)
    if isinstance(value, list):
        return [normalize_result(item) for item in value]
    if isinstance(value, dict):
        return {str(key): normalize_result(item) for key, item in value.items()}
    return value


def write_result_output(output: Path | None, payload: Any) -> None:
    """Write result to JSON or YAML file.
    
    Args:
        output: Output file path (None to skip)
        payload: Data to write
    """
    if output is None:
        return
    
    normalized = normalize_result(payload)
    output.parent.mkdir(parents=True, exist_ok=True)
    
    if output.suffix.lower() == ".json":
        output.write_text(json.dumps(normalized, indent=2, ensure_ascii=False))
    else:
        output.write_text(yaml.safe_dump(normalized, sort_keys=False, allow_unicode=True))


def build_html_sections(title: str, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Build HTML sections for quality reports.
    
    Args:
        title: Section title
        rows: Row data
        
    Returns:
        List of section dictionaries
    """
    if not rows:
        return [{"title": title, "columns": ["status"], "rows": [{"status": "empty"}]}]
    
    columns = list(rows[0].keys())
    return [{"title": title, "columns": columns, "rows": rows}]


def write_reports(
    *,
    title: str,
    summary: dict[str, Any],
    sections: list[dict[str, Any]],
    output_dir: Path,
) -> dict[str, Path]:
    """Write quality reports in multiple formats.
    
    Args:
        title: Report title
        summary: Summary data
        sections: Report sections
        output_dir: Output directory
        
    Returns:
        Dictionary of format -> file path
    """
    from logos_adk.quality_report import (
        generate_quality_report_csv,
        generate_quality_report_html,
        generate_quality_report_markdown,
    )
    
    output_dir.mkdir(parents=True, exist_ok=True)
    
    reports = {
        "html": generate_quality_report_html(title=title, summary=summary, sections=sections),
        "markdown": generate_quality_report_markdown(title=title, summary=summary, sections=sections),
        "csv": generate_quality_report_csv(sections=sections),
    }
    
    paths = {}
    for fmt, content in reports.items():
        path = output_dir / f"report.{fmt}"
        path.write_text(content)
        paths[fmt] = path
    
    return paths


__all__ = [
    "normalize_result",
    "write_result_output",
    "build_html_sections",
    "write_reports",
]
