"use client";
import { useCallback, useState } from "react";
/**
 * Behavior hook that generates and downloads usage data as CSV.
 *
 * Operates entirely client-side from data already in memory — no
 * additional RPC calls. Supports two formats:
 * - `daily_summary` — one row per day with date, executions, tokens, cost
 * - `model_breakdown` — one row per model with calls, tokens, cost
 *
 * @param report - The org usage report data (from `useOrgUsageReport`).
 * @param orgId - Organization ID for the filename.
 */
export function useExportCSV(report, orgId) {
    const [isExporting, setIsExporting] = useState(false);
    const exportCSV = useCallback((format) => {
        if (!report)
            return;
        setIsExporting(true);
        try {
            const { csv, filename } = format === "daily_summary"
                ? buildDailySummaryCSV(report, orgId)
                : buildModelBreakdownCSV(report, orgId);
            downloadCSV(csv, filename);
        }
        finally {
            setIsExporting(false);
        }
    }, [report, orgId]);
    return { exportCSV, isExporting };
}
function buildDailySummaryCSV(report, orgId) {
    const header = "Date,Executions,Tokens,Cost (USD)";
    const rows = report.dailyCosts.map((entry) => {
        const cost = (Number(entry.billableCostMicros) / 1_000_000).toFixed(6);
        return `${entry.date},${entry.executionCount},${entry.totalTokens},${cost}`;
    });
    return {
        csv: [header, ...rows].join("\n"),
        filename: `${orgId}-daily-usage.csv`,
    };
}
function buildModelBreakdownCSV(report, orgId) {
    const header = "Model,Provider,Calls,Input Tokens,Output Tokens,Cache Read Tokens,Cache Write Tokens,Cost (USD)";
    const rows = report.modelBreakdown.map((m) => {
        const cost = (Number(m.billableCostMicros) / 1_000_000).toFixed(6);
        return [
            escapeCsvField(m.model),
            escapeCsvField(m.provider),
            m.callCount,
            m.inputTokens,
            m.outputTokens,
            m.cacheReadInputTokens,
            m.cacheCreationInputTokens,
            cost,
        ].join(",");
    });
    return {
        csv: [header, ...rows].join("\n"),
        filename: `${orgId}-model-usage.csv`,
    };
}
function escapeCsvField(value) {
    if (value.includes(",") || value.includes('"') || value.includes("\n")) {
        return `"${value.replace(/"/g, '""')}"`;
    }
    return value;
}
function downloadCSV(csv, filename) {
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
}
//# sourceMappingURL=useExportCSV.js.map