// TokenScope persistence — writes breakdown to task records.
import type { Sql } from '../../db.js';
import type { TokenBreakdown } from './analyzer.js';

export async function persistTaskBreakdown(
  sql: Sql,
  taskId: string,
  breakdown: TokenBreakdown,
): Promise<void> {
  await sql`
    UPDATE tasks SET token_breakdown = ${sql.json(breakdown as never)}
    WHERE id = ${taskId}
  `;
}

export async function getTaskBreakdown(
  sql: Sql,
  taskId: string,
): Promise<TokenBreakdown | null> {
  const rows = await sql<{ token_breakdown: any }[]>`
    SELECT token_breakdown FROM tasks WHERE id = ${taskId}
  `;
  return rows[0]?.token_breakdown ?? null;
}

export async function analyzeAndPersistTaskBreakdown(
  sql: Sql,
  taskId: string,
  parts: any[],
): Promise<TokenBreakdown> {
  const { analyzeMessages } = await import('./analyzer.js');
  const breakdown = analyzeMessages(parts);
  await persistTaskBreakdown(sql, taskId, breakdown);
  return breakdown;
}
