import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

/**
 * Budget governor (Critics KG-12). Sums `IiosAiModelRun.costUnits` for a scope and
 * compares against a configured quota. When exceeded the caller degrades — the job
 * ABSTAINS and no artifact is produced — rather than letting AI cost run unbounded.
 */
@Injectable()
export class AiBudgetGuard {
  private quota = Number(process.env.IIOS_AI_BUDGET_UNITS ?? '1000000');

  constructor(private readonly prisma: PrismaService) {}

  /** Test/config hook to force a low quota. */
  setQuota(units: number): this {
    this.quota = units;
    return this;
  }

  async check(scopeId: string): Promise<{ ok: boolean; spent: number; quota: number }> {
    const agg = await this.prisma.iiosAiModelRun.aggregate({ _sum: { costUnits: true }, where: { scopeId } });
    const spent = agg._sum.costUnits ?? 0;
    return { ok: spent < this.quota, spent, quota: this.quota };
  }
}
