import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { SolutionChapterSchema } from '@/server/modules/solution-designs/solution-design.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { SolutionDesignService } from '@/server/modules/solution-designs/solution-design.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 路径参数Schema
const ApplyAIParams = z.object({
  id: z.string().openapi({
    param: { name: 'id', in: 'path' },
    example: '1',
    description: '方案设计ID'
  }),
  chapterId: z.string().openapi({
    param: { name: 'chapterId', in: 'path' },
    example: '1',
    description: '章节ID'
  })
});

// 请求Schema
const ApplyAIRequest = z.object({
  suggestions: z.array(z.string()).openapi({
    description: 'AI修改建议列表',
    example: ['建议增加具体数据支持', '优化段落结构']
  }),
  revisedContent: z.string().openapi({
    description: '修改后的内容',
    example: '优化后的章节内容...'
  }),
  confidence: z.number().openapi({
    description: '置信度评分（0-1）',
    example: 0.85
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'post',
  path: '/{id}/chapters/{chapterId}/apply-ai',
  middleware: [authMiddleware],
  request: {
    params: ApplyAIParams,
    body: {
      content: {
        'application/json': { schema: ApplyAIRequest }
      }
    }
  },
  responses: {
    200: {
      description: '成功应用AI修改',
      content: { 'application/json': { schema: SolutionChapterSchema } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '方案设计或章节不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { id, chapterId } = c.req.valid('param');
    const aiData = await c.req.json();
    const user = c.get('user');
    
    const service = new SolutionDesignService(AppDataSource);
    
    // 先检查权限
    const existingDesign = await service.getById(Number(id));
    if (!existingDesign) {
      return c.json({ code: 404, message: '方案设计不存在' }, 404);
    }

    if (existingDesign.userId !== user.id) {
      return c.json({ code: 403, message: '无权操作此方案设计' }, 403);
    }

    // 应用AI修改
    const updatedChapter = await service.applyAIModifications(
      Number(chapterId),
      aiData
    );

    // 更新进度
    await service.updateProgress(Number(id));

    return c.json(updatedChapter, 200);

  } catch (error) {
    console.error('应用AI修改失败:', error);
    const { code = 500, message = '应用AI修改失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;