import { createDbService } from '@/server/services/db.js';
/**
 * Backfill scheduler — Plan 4 Task 9/10.
 *
 * Fans out enqueueDealTranslation for all APPROVED deals with staggered
 * scheduledAt to respect ratePerMin.
 */
import { deals, translationJobs } from '@/server/db/schema.js';
import { eq, sql } from 'drizzle-orm';
import { env } from '@/server/env.js';
import { enqueueDealTranslation } from '@/server/translation/jobs/enqueue.js';
import { getSystemConfig } from '@/server/db/queries/system-config.js';

export interface BackfillOpts {
  locale: string;
  ratePerMin: number;
  dryRun?: boolean;
}

export interface BackfillResult {
  count: number;
  dryRun: boolean;
}

export async function enqueueBackfill(opts: BackfillOpts): Promise<BackfillResult> {
  const db = createDbService({ DATABASE_URL: env.DATABASE_URL });

  const dealRows = await db
    .select({ id: deals.id })
    .from(deals)
    .where(eq(deals.dealState, 'ACTIVE'));

  if (opts.dryRun) {
    return { count: dealRows.length, dryRun: true };
  }

  const now = Date.now();
  const intervalMs = Math.max(1, Math.floor(60_000 / opts.ratePerMin));

  let i = 0;
  for (const row of dealRows) {
    await enqueueDealTranslation(db, row.id, {
      targetLocales: [opts.locale],
      scheduledAt: new Date(now + i * intervalMs),
    });
    i++;
  }

  return { count: i, dryRun: false };
}

/**
 * Cost estimator — returns estimated cost and time for backfilling a locale.
 * Uses translation_price_usd_per_kchar from system_config.
 */
export interface CostEstimate {
  dealCount: number;
  estimatedKchars: number;
  estimatedCostUsd: number;
  estimatedMinutes: number;
  pricePerKchar: number;
  ratePerMin: number;
}

export async function estimateBackfillCost(opts: {
  locale: string;
  ratePerMin: number;
}): Promise<CostEstimate> {
  const db = createDbService({ DATABASE_URL: env.DATABASE_URL });

  const [dealRows, priceStr] = await Promise.all([
    db.select({ id: deals.id }).from(deals).where(eq(deals.dealState, 'ACTIVE')),
    getSystemConfig(db, 'translation_price_usd_per_kchar'),
  ]);

  const pricePerKchar = parseFloat(priceStr) || 0.001;
  const dealCount = dealRows.length;
  // Average estimate: ~500 chars per deal (title ~80 + description ~420)
  const estimatedKchars = (dealCount * 500) / 1000;
  const estimatedCostUsd = estimatedKchars * pricePerKchar;
  const estimatedMinutes = dealCount / opts.ratePerMin;

  return {
    dealCount,
    estimatedKchars,
    estimatedCostUsd,
    estimatedMinutes,
    pricePerKchar,
    ratePerMin: opts.ratePerMin,
  };
}

/**
 * Backfill progress query.
 */
export interface BackfillProgress {
  locale: string;
  total: number;
  done: number;
  failed: number;
  pending: number;
  running: number;
  etaSeconds: number;
}

export async function getBackfillProgress(locale: string): Promise<BackfillProgress> {
  const db = createDbService({ DATABASE_URL: env.DATABASE_URL });

  const rows = await db
    .select({ status: translationJobs.status, cnt: sql<number>`count(*)::int` })
    .from(translationJobs)
    .where(eq(translationJobs.targetLocale, locale))
    .groupBy(translationJobs.status);

  const byStatus: Record<string, number> = {};
  for (const r of rows) byStatus[r.status] = r.cnt;

  const done = byStatus['DONE'] ?? 0;
  const failed = byStatus['FAILED'] ?? 0;
  const pending = byStatus['PENDING'] ?? 0;
  const running = byStatus['RUNNING'] ?? 0;
  const total = Object.values(byStatus).reduce((a, b) => a + b, 0);

  // Naive ETA: assume 1 job/sec processing rate
  const etaSeconds = (pending + running) * 1;

  return { locale, total, done, failed, pending, running, etaSeconds };
}
