import { computed, type Ref } from 'vue';

import type { Agent } from './agents'; // Import Agent interface

export function formatUsage(u: any, agentId: string | null = null, allAgents: Agent[] | null = null): string {
    if (!u) return '';
    const inn = u.input_tokens ?? u.in ?? null;
    const out = u.output_tokens ?? u.out ?? null;

    let inCost = 0, outCost = 0, totalCost = 0;
    if (agentId && allAgents && inn !== null && out !== null) {
        const agent = allAgents.find(a => a.id === agentId);
        if (agent && agent.promptPrice !== null && agent.completionPrice !== null) {
            inCost = (inn / 1_000_000) * agent.promptPrice;
            outCost = (out / 1_000_000) * agent.completionPrice;
            totalCost = inCost + outCost;
        }
    }

    // Fallback to existing cost from backend if no agent pricing
    if (totalCost === 0) {
        totalCost = typeof u.cost === 'object' ? (u.cost?.total ?? 0) : Number(u.cost || 0);
    }

    const showCosts = totalCost > 0.0000001;
    const inCostStr = showCosts && inCost > 0 ? `$${inCost.toFixed(4)}` : '';
    const outCostStr = showCosts && outCost > 0 ? `$${outCost.toFixed(4)}` : '';

    if (inn !== null && out !== null) {
        const inFmt = inn >= 1000 ? (inn / 1000).toFixed(1) + 'k' : String(inn);
        const outFmt = out >= 1000 ? (out / 1000).toFixed(1) + 'k' : String(out);
        
        let pricingStr = '';
        if (agentId && allAgents) {
            const agent = allAgents.find(a => a.id === agentId);
            if (agent && agent.promptPrice !== null && agent.completionPrice !== null) {
                pricingStr = ` (${agent.promptPrice.toFixed(2)}/${agent.completionPrice.toFixed(2)})`;
            }
        }

        const parts = [`${inFmt} in${inCostStr ? ` (${inCostStr})` : ''}`, `${outFmt} out${outCostStr ? ` (${outCostStr})` : ''}`];
        if (showCosts) parts.push(`$${totalCost.toFixed(4)}${pricingStr}`);
        return parts.join(' · ');
    }
    const total = u.total_tokens ?? u.total ?? 0;
    return `${total} tokens${showCosts ? ` · $${totalCost.toFixed(4)}` : ''}`;
}

import pkg from '../../package.json';

declare const __BUILD__: string;

export function useUI(status: Ref<string>) {
    const version: string = `${pkg.version}-${__BUILD__}`;

    const statusClass = computed<string>(() => {
        if (status.value.includes('Connected')) return 'connected';
        if (status.value.includes('Connecting')) return 'connecting';
        if (status.value.includes('Error')) return 'error';
        return '';
    });

    return { version, statusClass };
}
