/**
 * cost-tracker.js — Stop Hook
 * 追蹤 Token 用量與估算成本。定價已更新為 Claude 4.x。
 */
const fs = require('fs');
const os = require('os');
const path = require('path');
let d = '';
process.stdin.on('data', c => d += c);
process.stdin.on('end', () => {
  try {
    const i = JSON.parse(d);
    const inputTokens = i.usage?.input_tokens || i.input_tokens || 0;
    const outputTokens = i.usage?.output_tokens || i.output_tokens || 0;
    const model = i.model || 'unknown';
    // 定價 [input per M USD, output per M USD]（2025 官方定價）
    const pricing = {
      'claude-haiku-4-5': [0.8, 4],
      'claude-sonnet-4-6': [3, 15],
      'claude-opus-4-7': [15, 75],
      'claude-3-haiku': [0.8, 4],
      'claude-3-sonnet': [3, 15],
      'claude-3-opus': [15, 75],
    };
    const matchedKey = Object.keys(pricing).find(k => model.includes(k)) || null;
    const [inputRate, outputRate] = matchedKey ? pricing[matchedKey] : [3, 15];
    const cost = (inputTokens * inputRate + outputTokens * outputRate) / 1_000_000;
    const metricsDir = path.join(os.homedir(), '.claude', 'metrics');
    if (!fs.existsSync(metricsDir)) fs.mkdirSync(metricsDir, { recursive: true });
    fs.appendFileSync(
      path.join(metricsDir, 'costs.jsonl'),
      JSON.stringify({ timestamp: new Date().toISOString(), model, input_tokens: inputTokens, output_tokens: outputTokens, cost_usd: cost.toFixed(6) }) + '\n'
    );
  } catch (e) {}
  process.stdout.write(d);
});
