import Router from '@koa/router';
import { logService, LogLevel } from '../services/log.service';
import { requestLogger } from '../services/requestLogger';
import { Context } from 'koa';

const router = new Router();

// 获取请求日志列表
router.get('/logs', async (ctx: Context) => {
  const { level, path, status, startTime, endTime, limit = 100, offset = 0 } = ctx.query;

  const filter: any = {};

  if (level && Object.values(LogLevel).includes(level as LogLevel)) {
    filter.level = level;
  }
  if (path) {
    filter.path = path as string;
  }
  if (status) {
    filter.status = parseInt(status as string, 10);
  }
  if (startTime) {
    filter.startTime = new Date(startTime as string);
  }
  if (endTime) {
    filter.endTime = new Date(endTime as string);
  }

  const logs = logService.getLogs(filter);
  const total = logs.length;
  const paginatedLogs = logs.slice(Number(offset), Number(offset) + Number(limit));

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      logs: paginatedLogs,
      total,
      limit: Number(limit),
      offset: Number(offset)
    }
  };
});

// 获取错误日志
router.get('/logs/errors', async (ctx: Context) => {
  const { limit = 50 } = ctx.query;
  const errors = logService.getRecentErrors(Number(limit));

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      errors,
      count: errors.length
    }
  };
});

// 获取错误分析
router.get('/logs/errors/analyze', async (ctx: Context) => {
  const analyses = logService.analyzeErrors();

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      analyses,
      total: analyses.length
    }
  };
});

// 获取最新错误详情
router.get('/logs/errors/latest', async (ctx: Context) => {
  const errors = logService.getRecentErrors(1);

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      error: errors.length > 0 ? errors[0] : null
    }
  };
});

// 自动分析单条错误并提供修复建议
router.post('/logs/auto-fix', async (ctx: Context) => {
  const { error, path, method } = ctx.request.body as any;

  if (!error) {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: '缺少错误信息',
      data: null
    };
    return;
  }

  // 创建临时日志对象用于分析
  const tempLog = {
    error,
    path: path || 'unknown',
    timestamp: new Date()
  } as any;

  const suggestions = logService.autoAnalyzeError(tempLog);

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      error,
      suggestions,
      path,
      method
    }
  };
});

// 执行自动修复（模拟）
router.post('/logs/fix/:errorId', async (ctx: Context) => {
  const { errorId } = ctx.params;

  // 这里可以根据errorId执行不同的修复操作
  // 目前是模拟实现
  const fixResults: Record<string, any> = {
    'DB_CONNECTION': {
      success: true,
      action: 'restart_database_connection',
      message: '已重新初始化数据库连接池'
    },
    'JSON_PARSE': {
      success: true,
      action: 'validate_request_body',
      message: '已添加请求体验证中间件'
    },
    'VALIDATION': {
      success: true,
      action: 'sanitize_parameters',
      message: '已添加参数清理逻辑'
    },
    'FILE_NOT_FOUND': {
      success: true,
      action: 'create_default_file',
      message: '已创建默认文件'
    },
    'PERMISSION': {
      success: true,
      action: 'refresh_token',
      message: '已刷新用户权限'
    },
    'TIMEOUT': {
      success: true,
      action: 'increase_timeout',
      message: '已增加超时时间'
    }
  };

  const result = fixResults[errorId] || {
    success: false,
    action: 'unknown',
    message: '未知的错误类型，无法自动修复'
  };

  ctx.body = {
    code: 0,
    message: 'success',
    data: result
  };
});

// 获取统计数据
router.get('/logs/stats', async (ctx: Context) => {
  const stats = logService.getStats();

  ctx.body = {
    code: 0,
    message: 'success',
    data: stats
  };
});

// 清除日志
router.delete('/logs', async (ctx: Context) => {
  const { olderThanHours } = ctx.query;

  const removed = logService.clearLogs(
    olderThanHours ? parseInt(olderThanHours as string, 10) : undefined
  );

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      removed,
      remaining: logService.getLogs().length
    }
  };
});

// 测试接口 - 故意产生错误用于测试
router.post('/logs/test-error', async (ctx: Context) => {
  const { type = 'TEST' } = ctx.request.body as any;

  if (type === 'DB_CONNECTION') {
    throw new Error('ECONNREFUSED: Connection refused');
  } else if (type === 'JSON_PARSE') {
    throw new Error('JSON.parse: Unexpected token at position 0');
  } else if (type === 'VALIDATION') {
    ctx.status = 400;
    ctx.body = {
      code: 400,
      message: 'validation failed: field "name" is required'
    };
    return;
  } else if (type === 'FILE_NOT_FOUND') {
    throw new Error('ENOENT: no such file or directory \'uploads/test.txt\'');
  } else if (type === 'PERMISSION') {
    throw new Error('EACCES: permission denied');
  } else if (type === 'TIMEOUT') {
    throw new Error('ETIMEDOUT: connection timeout after 30000ms');
  }

  ctx.body = {
    code: 0,
    message: '测试错误已记录'
  };
});

export default router;