import type { FastifyInstance } from 'fastify';
import { withTenant } from '../data/db.js';
import { GovernanceEngine } from '../governance/engine.js';

const engine = new GovernanceEngine();

export function registerGovernanceRoutes(app: FastifyInstance) {
  // Get governance status
  app.get('/api/v1/governance', async (req, reply) => {
    const tenantId = (req as any).tenantId;

    const result = await withTenant(tenantId, async (client) => {
      return client.query('SELECT governance_mode, governance_started_at FROM tenants WHERE id = $1', [tenantId]);
    });

    const tenant = result.rows[0];
    if (!tenant) return reply.status(404).send({ error: 'Tenant not found' });

    const daysInMode = Math.floor((Date.now() - new Date(tenant.governance_started_at).getTime()) / (86400 * 1000));

    return {
      mode: tenant.governance_mode,
      days_in_mode: daysInMode,
      started_at: tenant.governance_started_at,
    };
  });

  // Check promotion eligibility
  app.get('/api/v1/governance/promotion', async (req, reply) => {
    const tenantId = (req as any).tenantId;

    const result = await withTenant(tenantId, async (client) => {
      const tenant = await client.query('SELECT governance_mode, governance_started_at FROM tenants WHERE id = $1', [tenantId]);
      const t = tenant.rows[0];
      if (!t) return null;

      // Calculate FP rate from last 30 days
      const fpStats = await client.query(`
        SELECT
          COUNT(*) FILTER (WHERE status = 'expected')::float /
          NULLIF(COUNT(*)::float, 0) as fp_rate
        FROM anomalies
        WHERE detected_at > now() - interval '30 days'
      `);

      return { tenant: t, fpRate: fpStats.rows[0]?.fp_rate ?? 0 };
    });

    if (!result) return reply.status(404).send({ error: 'Tenant not found' });

    const daysInMode = Math.floor((Date.now() - new Date(result.tenant.governance_started_at).getTime()) / (86400 * 1000));
    const evaluation = engine.evaluatePromotion(tenantId, {
      fpRate: result.fpRate,
      daysInCurrentMode: daysInMode,
    });

    return { ...evaluation, current_mode: result.tenant.governance_mode, fp_rate: result.fpRate, days_in_mode: daysInMode };
  });
}
