import { Hono } from 'hono';
import { AgentHeartbeatSchema, AgentActivityQuerySchema } from '../types/index';
import * as agentService from '../services/agent.service';

export const agentsRouter = new Hono();

// ─── GET /v1/agents ─────────────────────────────────────
// List all agents with health status
agentsRouter.get('/', async (c) => {
  try {
    const items = await agentService.listAgents();
    return c.json({ success: true, data: items });
  } catch (err: any) {
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── GET /v1/agents/:id ────────────────────────────────
// Agent details + current task + metrics
agentsRouter.get('/:id', async (c) => {
  try {
    const agent = await agentService.getAgent(c.req.param('id'));

    if (!agent) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: 'Agent not found' } },
        404
      );
    }

    return c.json({ success: true, data: agent });
  } catch (err: any) {
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── POST /v1/agents/:id/heartbeat ─────────────────────
// Agent reports its status
agentsRouter.post('/:id/heartbeat', async (c) => {
  try {
    const body = AgentHeartbeatSchema.parse(await c.req.json());
    const agentId = c.req.param('id');

    const updated = await agentService.heartbeat(agentId, body);

    if (!updated) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: 'Agent not found' } },
        404
      );
    }

    return c.body(null, 204);
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json(
        { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid input', details: err.errors } },
        400
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});

// ─── GET /v1/agents/:id/activity ────────────────────────
// Activity log for an agent
agentsRouter.get('/:id/activity', async (c) => {
  try {
    const query = AgentActivityQuerySchema.parse(c.req.query());
    const agentId = c.req.param('id');

    // Verify agent exists
    const agent = await agentService.getAgent(agentId);
    if (!agent) {
      return c.json(
        { success: false, error: { code: 'NOT_FOUND', message: 'Agent not found' } },
        404
      );
    }

    const activity = await agentService.getAgentActivity(agentId, query);
    return c.json({ success: true, data: activity });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json(
        { success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid query', details: err.errors } },
        400
      );
    }
    return c.json(
      { success: false, error: { code: 'INTERNAL_ERROR', message: err.message } },
      500
    );
  }
});
