import { z } from 'zod';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';

export function registerPrompts(server: McpServer): void {
  server.registerPrompt(
    'new-feature',
    {
      title: 'New Feature',
      description:
        'Guides the agent through implementing a new feature: detect the framework, scaffold/implement code, run tests, and verify in a browser.',
      argsSchema: {
        name: z
          .string()
          .min(1)
          .describe('Short name of the feature, e.g. "user-profile" or "todo-list".'),
        description: z
          .string()
          .optional()
          .describe('A one-sentence description of what the feature should do.'),
      },
    },
    async ({ name, description }) => ({
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: [
              `Implement a new feature called "${name}".${description ? ` ${description}` : ''}`,
              '',
              'Follow this workflow:',
              '1. Call detect_framework to understand the workspace (backend, frontend, or both).',
              '2. If needed, scaffold the relevant pieces (e.g. generate_component, generate_api_route, or generate_laravel_resource).',
              '3. Implement the feature code, keeping existing conventions and not escaping the workspace root.',
              '4. Run run_tests and/or run_lint to validate the change.',
              '5. If a frontend exists, start_dev_server and browser_navigate/screenshot to verify the UI visually.',
              '6. Return a concise summary of files changed, test results, and any remaining TODOs.',
            ].join('\n'),
          },
        },
      ],
    }),
  );

  server.registerPrompt(
    'new-laravel-resource',
    {
      title: 'New Laravel Resource',
      description:
        'Guides the agent through scaffolding a full Laravel resource, running migrations, writing a feature test, and verifying routes.',
      argsSchema: {
        name: z.string().min(1).describe('Resource name, e.g. "Post" or "Order".'),
      },
    },
    async ({ name }) => ({
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: [
              `Create a new Laravel API resource for "${name}".`,
              '',
              'Workflow:',
              `1. Call generate_laravel_resource with name "${name}" and api: true.`,
              '2. Run artisan migrate (or artisan with command migrate and confirm: true) to create the table.',
              '3. Fill in the migration fields and model $fillable based on the resource requirements.',
              '4. Write a feature test with artisan make:test and run it via run_phpunit or run_pest.',
              '5. Verify the routes with artisan route:list.',
              '6. Optionally use laravel_tinker_eval to inspect a model instance.',
            ].join('\n'),
          },
        },
      ],
    }),
  );

  server.registerPrompt(
    'new-codeigniter-resource',
    {
      title: 'New CodeIgniter Resource',
      description:
        'Guides the agent through scaffolding a full CodeIgniter 4 resource, running migrations, and writing a test.',
      argsSchema: {
        name: z.string().min(1).describe('Resource name, e.g. "Post" or "Order".'),
      },
    },
    async ({ name }) => ({
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: [
              `Create a new CodeIgniter 4 resource for "${name}".`,
              '',
              'Workflow:',
              `1. Call generate_codeigniter_resource with name "${name}".`,
              '2. Run spark migrate to create the table.',
              '3. Fill in the migration fields and model properties as needed.',
              '4. Write a test with spark make:test and run it via run_codeigniter_tests.',
              '5. Verify the routes with spark routes.',
            ].join('\n'),
          },
        },
      ],
    }),
  );

  server.registerPrompt(
    'new-react-component',
    {
      title: 'New React Component',
      description:
        'Guides the agent through generating a React component, wiring it into a route/page, and verifying it in the browser.',
      argsSchema: {
        name: z.string().min(1).describe('Component name, e.g. "UserProfile".'),
        route: z.string().optional().describe('Optional route path to wire the component to, e.g. "/users".'),
      },
    },
    async ({ name, route }) => ({
      messages: [
        {
          role: 'user',
          content: {
            type: 'text',
            text: [
              `Create a new React component called "${name}"${route ? ` and wire it to route "${route}"` : ''}.`,
              '',
              'Workflow:',
              `1. Call generate_component (or generate_react_component) with name "${name}" and withTest: true.`,
              route ? `2. Call add_react_route with path "${route}" and component "${name}".` : '2. (No route requested) Add the component to the appropriate existing page or parent component.',
              '3. Run run_tests to verify the component test passes.',
              '4. Start the dev server with start_dev_server, navigate with browser_navigate, and capture a browser_screenshot to verify the UI.',
            ].join('\n'),
          },
        },
      ],
    }),
  );

  server.registerPrompt(
    'visual-diff-ci',
    {
      title: 'Visual Diff CI',
      description:
        'Guides the agent through a CI-style visual regression check: baselines, live screenshots, and browser_visual_diff thresholds.',
      argsSchema: {
        url: z.string().min(1).describe('Page URL to check, e.g. http://127.0.0.1:5173/'),
        baseline: z
          .string()
          .optional()
          .describe('Baseline name under .web-dev-mcp/baselines/ (without .png). Defaults to "home".'),
        thresholdPercent: z
          .string()
          .optional()
          .describe('Max allowed mismatch percent as a string, e.g. "0.5". Defaults to "1".'),
      },
    },
    async ({ url, baseline, thresholdPercent }) => {
      const name = baseline?.trim() || 'home';
      const threshold = thresholdPercent?.trim() || '1';
      return {
        messages: [
          {
            role: 'user',
            content: {
              type: 'text',
              text: [
                `Run a visual regression check for "${url}" against baseline "${name}" (fail if mismatch > ${threshold}%).`,
                '',
                'Workflow:',
                '1. Call detect_framework (and start_dev_server if the URL is a local app that is not already running).',
                `2. Call browser_navigate with url "${url}".`,
                `3. If .web-dev-mcp/baselines/${name}.png is missing, call browser_screenshot_baseline with name "${name}" and treat this run as baseline creation (report that CI should re-run on the next change).`,
                `4. Otherwise call browser_visual_diff with name "${name}" (and the same page still open).`,
                `5. If mismatchPercent > ${threshold}, treat as FAILED: keep the diff PNG path in the summary and list likely UI regressions.`,
                `6. If mismatchPercent <= ${threshold}, treat as PASSED.`,
                '7. Return a concise CI-style summary: baseline name, mismatch %, pass/fail, and artifact paths.',
              ].join('\n'),
            },
          },
        ],
      };
    },
  );
}
