/**
 * Blocking Page Rules - detect CAPTCHAs, bot-checks, and access-denied pages.
 */

import type { HintRule } from '../hint-engine';

export const blockingPageRules: HintRule[] = [
  {
    name: 'captcha-detected',
    priority: 120,
    match(ctx) {
      if (ctx.toolName !== 'navigate') return null;
      if (ctx.isError) return null;
      if (/"blockingPage"\s*:\s*\{[^}]*"type"\s*:\s*"captcha"/i.test(ctx.resultText)) {
        // If CAPTCHA was already auto-solved, don't fire the hint
        if (/"captcha_solved"\s*:\s*true/.test(ctx.resultText)) return null;

        const typeMatch = ctx.resultText.match(/"captchaType"\s*:\s*"([^"]+)"/);
        const captchaType = typeMatch ? typeMatch[1] : 'unknown';
        const canAutoSolve = process.env.OPENCHROME_CAPTCHA_API_KEY &&
          process.env.OPENCHROME_CAPTCHA_AUTO_SOLVE === 'true';

        return canAutoSolve
          ? 'Hint: CAPTCHA detected (type: ' + captchaType + '). Auto-solve is active and will attempt to dismiss it. Wait for the result before retrying.'
          : 'Hint: CAPTCHA detected (type: ' + captchaType + '). ' +
            'STOP all interaction attempts with this page. ' +
            'Ask the user to solve the CAPTCHA in their Chrome browser, then use wait_for to detect when the page changes, and resume automation.';
      }
      return null;
    },
  },
  {
    name: 'bot-check-detected',
    priority: 121,
    match(ctx) {
      if (ctx.toolName !== 'navigate') return null;
      if (ctx.isError) return null;
      if (/"blockingPage"\s*:\s*\{[^}]*"type"\s*:\s*"bot-check"/i.test(ctx.resultText)) {
        return 'Hint: Bot verification detected. OpenChrome cannot bypass bot checks. Ask the user to complete the verification in their Chrome browser, then retry navigation.';
      }
      return null;
    },
  },
  {
    name: 'access-denied-detected',
    priority: 122,
    match(ctx) {
      if (ctx.toolName !== 'navigate') return null;
      if (ctx.isError) return null;
      if (/"blockingPage"\s*:\s*\{[^}]*"type"\s*:\s*"access-denied"/i.test(ctx.resultText)) {
        return 'Hint: Access denied (403/Forbidden). The site may be blocking automated access. Ask the user to verify they have permission to access this URL, or try navigating in their Chrome browser first.';
      }
      return null;
    },
  },
];
