"""
Export functies voor Elephate CLI

Bevat functies voor:
- JSON export
- CSV export (per categorie)
"""

import json
import csv
import os
from datetime import datetime
from typing import Dict, Any, List
from pathlib import Path


def export_json(
    results: Dict[str, Any],
    output_dir: str = "./elephate-output",
    filename: str = "resultaat.json"
) -> str:
    """
    Exporteer resultaten naar JSON.

    Args:
        results: Calculatie resultaten
        output_dir: Output directory
        filename: Bestandsnaam

    Returns:
        Pad naar het gemaakte bestand
    """
    Path(output_dir).mkdir(parents=True, exist_ok=True)

    output_path = os.path.join(output_dir, filename)

    export_data = {
        "export_info": {
            "tool": "Elephate CLI",
            "version": "0.1.0",
            "timestamp": datetime.now().isoformat(),
            "is_mock_data": True
        },
        "results": results
    }

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(export_data, f, indent=2, ensure_ascii=False)

    return output_path


def export_csv(
    results: Dict[str, Any],
    output_dir: str = "./elephate-output/csv"
) -> List[str]:
    """
    Exporteer resultaten naar CSV bestanden (één per categorie).

    Args:
        results: Calculatie resultaten
        output_dir: Output directory

    Returns:
        Lijst van paden naar gemaakte bestanden
    """
    Path(output_dir).mkdir(parents=True, exist_ok=True)

    created_files = []
    categories = results.get("categories", {})

    for cat_code, cat_data in categories.items():
        items = cat_data.get("items", [])
        if not items:
            continue

        # Maak bestandsnaam van categorie naam
        cat_name = cat_data.get("category", cat_code).lower()
        cat_name = cat_name.replace(" ", "_").replace("/", "-")
        filename = f"{cat_name}.csv"
        output_path = os.path.join(output_dir, filename)

        # Schrijf CSV
        fieldnames = [
            "code",
            "stabu_code",
            "description",
            "quantity",
            "unit",
            "unit_price",
            "total_price",
            "labor_hours"
        ]

        with open(output_path, "w", newline="", encoding="utf-8") as f:
            writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction="ignore")
            writer.writeheader()
            writer.writerows(items)

        created_files.append(output_path)

    # Schrijf ook een totalen bestand
    totals_path = os.path.join(output_dir, "totalen.csv")
    totals = results.get("totals", {})

    with open(totals_path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["Metriek", "Waarde"])
        writer.writerow(["Totaal items", totals.get("total_items", 0)])
        writer.writerow(["Totale kosten", f"€ {totals.get('total_cost', 0):.2f}"])
        writer.writerow(["Totale arbeidsuren", totals.get("total_labor_hours", 0)])
        writer.writerow(["Documenten verwerkt", totals.get("documents_processed", 0)])
        writer.writerow(["Export datum", datetime.now().isoformat()])
        writer.writerow(["Mock data", "Ja"])

    created_files.append(totals_path)

    return created_files


def get_export_summary(json_path: str, csv_paths: List[str]) -> List[str]:
    """
    Maak een lijst van alle geëxporteerde bestanden voor display.

    Returns:
        Lijst van relatieve paden
    """
    files = [json_path]
    files.extend(csv_paths)
    return files
