import { Router } from 'express';
import { INTEGRATION_CATALOG, CATALOG_BY_ID } from '../../shared/integrationCatalog.js';
import * as composioService from '../services/composio.js';

const router = Router();

/**
 * GET /api/composio/status
 * Check if Composio is configured and available.
 */
router.get('/status', async (req, res) => {
  res.json({ available: await composioService.isAvailable() });
});

/**
 * GET /api/composio/catalog
 * Returns the integration catalog with per-user connection status.
 */
router.get('/catalog', async (req, res) => {
  try {
    let connectedApps = {};
    const available = await composioService.isAvailable();

    if (available) {
      const accounts = await composioService.listConnectedAccounts(req.user.id);
      for (const acc of accounts) {
        if ((acc.status || '').toUpperCase() === 'ACTIVE') {
          connectedApps[acc.appName.toUpperCase()] = { id: acc.id, status: acc.status };
        }
      }
    }

    const catalog = INTEGRATION_CATALOG.map(integration => ({
      ...integration,
      connected: !!connectedApps[integration.id],
      connectionId: connectedApps[integration.id]?.id || null,
    }));

    res.json({ catalog, composioAvailable: available });
  } catch (err) {
    res.status(500).json({ error: 'Failed to load catalog' });
  }
});

/**
 * GET /api/composio/connections
 * List user's connected accounts.
 */
router.get('/connections', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.json({ connections: [], available: false });
  }

  try {
    const connections = await composioService.listConnectedAccounts(req.user.id);
    res.json({ connections });
  } catch (err) {
    res.status(500).json({ error: 'Failed to list connections' });
  }
});

/**
 * POST /api/composio/connect
 * Initiate OAuth for an integration.
 * Body: { appName, authConfigId? }
 */
router.post('/connect', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.status(503).json({ error: 'Composio not configured' });
  }

  const { appName, authConfigId } = req.body;
  if (!appName) return res.status(400).json({ error: 'appName required' });

  try {
    const result = await composioService.initiateConnection(req.user.id, appName, authConfigId);
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: 'Failed to initiate connection' });
  }
});

/**
 * POST /api/composio/connect/wait
 * Poll for OAuth completion.
 * Body: { connectedAccountId }
 */
router.post('/connect/wait', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.status(503).json({ error: 'Composio not configured' });
  }

  const { connectedAccountId } = req.body;
  if (!connectedAccountId) return res.status(400).json({ error: 'connectedAccountId required' });

  try {
    const result = await composioService.waitForConnection(connectedAccountId);
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: 'Failed to check connection status' });
  }
});

/**
 * DELETE /api/composio/connections/:id
 * Disconnect an account.
 */
router.delete('/connections/:id', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.status(503).json({ error: 'Composio not configured' });
  }

  try {
    await composioService.disconnectAccount(req.params.id);
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to disconnect' });
  }
});

/**
 * GET /api/composio/tools
 * Discover available tools.
 * Query: ?apps=GMAIL,SLACK
 */
router.get('/tools', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.status(503).json({ error: 'Composio not configured' });
  }

  const apps = req.query.apps ? req.query.apps.split(',').map(s => s.trim()) : [];
  try {
    const tools = await composioService.getTools(apps);
    res.json({ tools });
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch tools' });
  }
});

/**
 * GET /api/composio/tools/:slug/schema
 * Get schema for a specific tool action.
 */
router.get('/tools/:slug/schema', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.status(503).json({ error: 'Composio not configured' });
  }

  try {
    const schema = await composioService.getToolSchema(req.params.slug);
    res.json(schema);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch tool schema' });
  }
});

/**
 * POST /api/composio/tools/:slug/execute
 * Execute a tool action.
 * Body: { arguments: { ... } }
 */
router.post('/tools/:slug/execute', async (req, res) => {
  if (!(await composioService.isAvailable())) {
    return res.status(503).json({ error: 'Composio not configured' });
  }

  const { arguments: args } = req.body;
  try {
    const result = await composioService.executeTool(req.user.id, req.params.slug, args || {});
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: 'Failed to execute tool' });
  }
});

export default router;
