const openUrl = require('./openUrl');
const smartClick = require('./smartClick');
const smartType = require('./smartType');
const fillFormAuto = require('./fillFormAuto');
const smartWaitNavigation = require('./smartWaitNavigation');
const getButtons = require('./getButtons');
const getForms = require('./getForms');

const delay = (ms) => new Promise(res => setTimeout(res, ms));

module.exports = async ({ goal, data = {}, retries = 3 }) => {
  if (!goal) {
    throw new Error('Goal é obrigatório');
  }

  let log = [];
  let attempt = 0;

  const keywords = ['login', 'entrar', 'continuar', 'enviar', 'buscar', 'submit', 'ok', 'confirmar'];

  while (attempt < retries) {
    try {
      log.push(`Tentativa ${attempt + 1}`);

      if (goal.includes('http')) {
        await openUrl({ url: goal });
        log.push("Abriu URL");
        await delay(1500);
      }

      if (Object.keys(data).length > 0) {
        const forms = await getForms();

        if (forms.count > 0) {
          await fillFormAuto({ data });
          log.push("Formulário preenchido");
        }
      }

      const buttons = await getButtons();

      let clicked = false;

      for (const btn of buttons.buttons) {
        const match = keywords.find(k =>
          btn.text.toLowerCase().includes(k)
        );

        if (match) {
          await smartClick({ text: btn.text });
          await smartWaitNavigation({});
          log.push(`Clicou em: ${btn.text}`);
          clicked = true;
          break;
        }
      }

      if (!clicked && buttons.buttons.length > 0) {
        await smartClick({ text: buttons.buttons[0].text });
        await smartWaitNavigation({});
        log.push(`Fallback click: ${buttons.buttons[0].text}`);
      }

      return {
        success: true,
        action: "agent_flow_v2",
        attempts: attempt + 1,
        steps: log
      };

    } catch (error) {
      log.push(`Erro: ${error.message}`);
      attempt++;

      await delay(1000);
    }
  }

  return {
    success: false,
    action: "agent_flow_v2",
    attempts: attempt,
    steps: log
  };
};
