import { PageInfo } from './AgentContext';
import { InspectedElementInfo } from './inspectorActions';
import { toPascalCase } from 'config/routeRegistry';
import { resolvePagePaths } from './pagePathUtils';

export interface PromptOptions {
  skill: string | null;
  pageInfo: PageInfo;
  userPrompt: string;
  inspectedElement?: InspectedElementInfo | null;
}

/**
 * Generate a structured prompt for Claude Code
 */
export function generatePrompt(options: PromptOptions): string {
  const { skill, pageInfo, userPrompt, inspectedElement } = options;

  // ── Canvas 组件 prompt（独立分支，不走 CRUD 逻辑）
  if (inspectedElement?.type === 'canvas-component') {
    const componentType = inspectedElement.meta?.componentType ?? '';
    const code = inspectedElement.meta?.code ?? '';
    const parts: string[] = [];

    if (userPrompt.trim()) {
      parts.push(`请帮我实现这个功能：${userPrompt.trim()}`);
      parts.push('');
    }

    if (skill) {
      parts.push(
        `严格按照: ${skill} skill（位于 .claude/skills/${skill}/SKILL.md）描述的方法来完成代码的修改。如有不确定的地方，请先询问我，不要自己假设。`,
      );
      parts.push('');
    }

    const canvasItemId = inspectedElement.meta?.canvasItemId ?? '';
    parts.push('### 更多辅助信息：');
    parts.push(`- 组件类型: ${componentType}`);
    parts.push(`- Canvas Item ID: ${canvasItemId}`);
    parts.push('- 当前完整代码:');
    parts.push('```tsx');
    parts.push(code);
    parts.push('```');
    parts.push(
      '- 修改后按照 skill 的步骤通过 POST /canvas-patch 推送新代码，不要修改任何 .tsx 文件',
    );
    parts.push('');

    return parts.join('\n');
  }

  // ── 原有 CRUD prompt 逻辑
  const parts: string[] = [];
  // 1. User's request
  if (userPrompt.trim()) {
    parts.push(`请帮我实现这个功能：${userPrompt.trim()}`);
    parts.push('');
  }
  parts.push('');

  // 2. Skill specification (if available)
  if (skill) {
    parts.push(
      `严格按照: ${skill} skill 描述的方法来完成代码的修改。如有不确定的地方，请先询问我，不要自己假设。`,
    );
    parts.push('');
  }

  // 3. Inspected element context (from ElementInspector)
  if (inspectedElement) {
    const isAppHeader = inspectedElement.type === 'app-header';
    const isAppTitle = inspectedElement.type === 'app-title';
    const isGlobalUI = isAppHeader || isAppTitle;

    const paths = resolvePagePaths(
      pageInfo.sourceFilePath,
      pageInfo.resourceName,
      getFileName(pageInfo.pageType),
    );

    // Module name: prefer what the inspected element reports, fall back to sourceDir
    const moduleName = inspectedElement.resource || paths.sourceDir;

    parts.push('### 更多的辅助信息：');
    parts.push(`- 页面URL路径: ${pageInfo.path}`);
    if (!isGlobalUI && moduleName)
      parts.push(`- 所属的业务模块（模型）: ${toPascalCase(moduleName)}`);
    if (!isGlobalUI) parts.push(`- 页面类型: ${pageInfo.pageType}`);
    if (inspectedElement.field)
      parts.push(`- 字段名|列名: ${inspectedElement.field}`);
    if (isAppTitle) {
      parts.push(`- 标题文件路径: web/src/components/layout/title.tsx`);
      parts.push(`- Logo文件路径: web/src/components/layout/logo.tsx`);
    } else if (isAppHeader) {
      parts.push(`- header组件文件路径: web/src/components/layout/header.tsx`);
    } else {
      parts.push(`- 页面文件路径: ${paths.pageFilePath}`);
      parts.push(`- 页面ui配置文件路径: ${paths.uiConfigPath}`);
      parts.push(`- 页面后端api文件路径: ${paths.backendApiPath}`);
      parts.push(`- 页面对应的数据模型文件目录: ${paths.prismaDir}`);
    }
    parts.push('');
  }

  return parts.join('\n');
}

/**
 * Get the file name based on page type
 */
function getFileName(pageType: string): string {
  switch (pageType) {
    case 'list':
      return 'list.tsx';
    case 'create':
      return 'create.tsx';
    case 'edit':
      return 'edit.tsx';
    case 'show':
      return 'show.tsx';
    default:
      return '';
  }
}

/**
 * Generate a preview of the prompt (shorter version)
 */
export function generatePromptPreview(options: PromptOptions): string {
  const { skill, userPrompt } = options;
  const preview = userPrompt.trim().slice(0, 50);
  const skillPart = skill ? ` [${skill}]` : '';
  return `${skillPart}${preview ? `: ${preview}...` : ''}`;
}
