import { Router, Request, Response } from 'express';
import AutoPilotService from '../../services/AutoPilotService';
import AutoPilotScheduler from '../../services/AutoPilotScheduler';
import { logger } from '../../utils/logger';

const router = Router();

router.post('/autopilot/sessions', async (req: Request, res: Response) => {
  try {
    const tenantId = (req as any).user?.tenantId;
    const { shopId, mode, config } = req.body;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    if (!shopId || !mode || !config) {
      return res.status(400).json({
        success: false,
        message: 'shopId, mode, and config are required'
      });
    }

    const session = await AutoPilotService.createSession({
      tenantId,
      shopId,
      mode,
      config
    });

    res.status(201).json({
      success: true,
      data: session,
      message: 'Autopilot session created successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error creating session:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to create autopilot session'
    });
  }
});

router.post('/autopilot/sessions/:id/start', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const session = await AutoPilotService.startSession(id);

    res.json({
      success: true,
      data: session,
      message: 'Autopilot session started successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error starting session:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to start autopilot session'
    });
  }
});

router.post('/autopilot/sessions/:id/pause', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    await AutoPilotService.pauseSession(id);

    res.json({
      success: true,
      message: 'Autopilot session paused successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error pausing session:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to pause autopilot session'
    });
  }
});

router.post('/autopilot/sessions/:id/stop', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const session = await AutoPilotService.stopSession(id, tenantId);

    res.json({
      success: true,
      data: session,
      message: 'Autopilot session stopped successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error stopping session:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to stop autopilot session'
    });
  }
});

router.post('/autopilot/sessions/:id/unschedule', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    await AutoPilotScheduler.unscheduleSession(id);

    res.json({
      success: true,
      message: 'Autopilot session unscheduled successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error unscheduling session:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to unschedule autopilot session'
    });
  }
});

router.get('/autopilot/sessions', async (req: Request, res: Response) => {
  try {
    const tenantId = (req as any).user?.tenantId;
    const { status, limit, offset } = req.query;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    // 使用 getSessionsByTenant 替代 getSessions
    const sessions = await AutoPilotService.getSessionsByTenant(tenantId);

    res.json({
      success: true,
      data: sessions
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error fetching sessions:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to fetch autopilot sessions'
    });
  }
});

router.get('/autopilot/sessions/:id', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const session = await AutoPilotService.getSessionById(id);

    if (!session || session.tenant_id !== tenantId) {
      return res.status(404).json({
        success: false,
        message: 'Session not found'
      });
    }

    res.json({
      success: true,
      data: session
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error fetching session:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to fetch autopilot session'
    });
  }
});

router.get('/autopilot/sessions/:id/logs', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;
    const { limit, offset } = req.query;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const result = await AutoPilotService.getSessionLogs(id, {
      limit: limit ? parseInt(limit as string) : undefined,
      offset: offset ? parseInt(offset as string) : undefined
    });

    res.json({
      success: true,
      data: result
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error fetching session logs:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to fetch session logs'
    });
  }
});

router.get('/autopilot/sessions/:id/stats', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    // 获取会话统计信息 - 使用 getSessionById 和 getSessionLogs 组合
    const session = await AutoPilotService.getSessionById(id);
    if (!session || session.tenant_id !== tenantId) {
      return res.status(404).json({
        success: false,
        message: 'Session not found'
      });
    }

    const logs = await AutoPilotService.getSessionLogs(id, { limit: 1000 });

    const stats = {
      sessionId: id,
      status: session.status,
      totalLogs: logs.total,
      executionCount: logs.logs.filter((l: any) => l.log_type === 'TASK_EXECUTION').length,
      errorCount: logs.logs.filter((l: any) => l.log_type === 'ERROR').length,
      createdAt: session.created_at,
      updatedAt: session.updated_at
    };

    res.json({
      success: true,
      data: stats
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error fetching session stats:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to fetch session stats'
    });
  }
});

router.put('/autopilot/sessions/:id/config', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;
    const { config } = req.body;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    if (!config) {
      return res.status(400).json({
        success: false,
        message: 'config is required'
      });
    }

    const session = await AutoPilotService.updateSessionConfig(id, config);

    res.json({
      success: true,
      data: session,
      message: 'Session config updated successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error updating session config:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to update session config'
    });
  }
});

router.post('/autopilot/sessions/:id/execute-task', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;
    const { taskType, params } = req.body;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    if (!taskType) {
      return res.status(400).json({
        success: false,
        message: 'taskType is required'
      });
    }

    const result = await AutoPilotService.executeTask({
      sessionId: id,
      taskType,
      input: params || {}
    });

    res.json({
      success: true,
      data: result,
      message: 'Task executed successfully'
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error executing task:', error);
    res.status(400).json({
      success: false,
      message: error.message || 'Failed to execute task'
    });
  }
});

router.get('/autopilot/sessions/:id/schedule', async (req: Request, res: Response) => {
  try {
    const id = req.params.id as string;
    const tenantId = (req as any).user?.tenantId;

    if (!tenantId) {
      return res.status(400).json({
        success: false,
        message: 'Tenant ID not found'
      });
    }

    const schedule = await AutoPilotScheduler.getSessionSchedule(id);

    res.json({
      success: true,
      data: schedule
    });
  } catch (error: any) {
    logger.error('[AutoPilotRoutes] Error fetching session schedule:', error);
    res.status(500).json({
      success: false,
      message: error.message || 'Failed to fetch session schedule'
    });
  }
});

export default router;
