/**
 * Verify Routes
 *
 * Code verification/quality assurance endpoints.
 */

import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import type { AppContext } from '../router.js';
import { VerifyRequestSchema } from '../types.js';
import { VerifierManager } from '../../verifier/manager.js';

export const verifyRoutes = new Hono<AppContext>();

/**
 * POST /verify - Run all enabled verifiers
 */
verifyRoutes.post('/', zValidator('json', VerifyRequestSchema), async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();
  const body = c.req.valid('json');

  try {
    const manager = new VerifierManager({ repoRoot });

    // Filter by names if provided
    const report = body.verifierNames && body.verifierNames.length > 0
      ? await manager.runByNames(body.verifierNames, {
          goal: body.goal,
          changedFiles: body.filesChanged,
          gitDiff: body.gitDiff,
          cwd: repoRoot,
        })
      : await manager.runAll({
          goal: body.goal,
          changedFiles: body.filesChanged,
          gitDiff: body.gitDiff,
          cwd: repoRoot,
        });

    return c.json({
      success: report.allPassed,
      summary: report.summary,
      passedCount: report.passedCount,
      failedCount: report.failedCount,
      totalDuration: report.totalDuration,
      results: report.results.map((r) => ({
        name: r.name,
        passed: r.passed,
        duration: r.duration,
        output: r.output,
        error: r.error,
        issues: r.issues,
      })),
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * GET /verify/config - Get verifier configuration
 */
verifyRoutes.get('/config', async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();

  try {
    const manager = new VerifierManager({ repoRoot });
    const config = await manager.loadConfig();

    return c.json({
      maxAttempts: config.maxAttempts,
      verifiers: config.verifiers.map((v) => ({
        name: v.name,
        type: v.type,
        enabled: v.enabled,
        description: v.description,
      })),
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * GET /verify/enabled - Get list of enabled verifiers
 */
verifyRoutes.get('/enabled', async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();

  try {
    const manager = new VerifierManager({ repoRoot });
    const verifiers = await manager.getEnabledVerifiers();

    return c.json({
      verifiers: verifiers.map((v) => ({
        name: v.name,
        type: v.type,
        description: v.description,
      })),
      count: verifiers.length,
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * POST /verify/run/:name - Run a specific verifier
 */
verifyRoutes.post('/run/:name', async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();
  const { name } = c.req.param();

  try {
    const body = await c.req.json<{
      goal?: string;
      filesChanged?: string[];
      gitDiff?: string;
    }>().catch(() => ({}));

    const manager = new VerifierManager({ repoRoot });
    const report = await manager.runByNames([name], {
      goal: body.goal,
      changedFiles: body.filesChanged,
      gitDiff: body.gitDiff,
      cwd: repoRoot,
    });

    if (report.results.length === 0) {
      return c.json({ error: `Verifier not found: ${name}` }, 404);
    }

    const result = report.results[0];
    return c.json({
      name: result.name,
      passed: result.passed,
      duration: result.duration,
      output: result.output,
      error: result.error,
      issues: result.issues,
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * PUT /verify/config/:name/enable - Enable a verifier
 */
verifyRoutes.put('/config/:name/enable', async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();
  const { name } = c.req.param();

  try {
    const manager = new VerifierManager({ repoRoot });
    const success = await manager.setEnabled(name, true);

    if (!success) {
      return c.json({ error: `Verifier not found: ${name}` }, 404);
    }

    return c.json({
      success: true,
      message: `Verifier "${name}" enabled`,
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * PUT /verify/config/:name/disable - Disable a verifier
 */
verifyRoutes.put('/config/:name/disable', async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();
  const { name } = c.req.param();

  try {
    const manager = new VerifierManager({ repoRoot });
    const success = await manager.setEnabled(name, false);

    if (!success) {
      return c.json({ error: `Verifier not found: ${name}` }, 404);
    }

    return c.json({
      success: true,
      message: `Verifier "${name}" disabled`,
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});

/**
 * DELETE /verify/config/:name - Remove a verifier
 */
verifyRoutes.delete('/config/:name', async (c) => {
  const repoRoot = c.get('repoRoot') ?? process.cwd();
  const { name } = c.req.param();

  try {
    const manager = new VerifierManager({ repoRoot });
    const success = await manager.removeVerifier(name);

    if (!success) {
      return c.json({ error: `Verifier not found: ${name}` }, 404);
    }

    return c.json({
      success: true,
      message: `Verifier "${name}" removed`,
    });
  } catch (error) {
    return c.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      500
    );
  }
});
