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');

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

  let log = [];

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

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

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

    const buttons = await getButtons();

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

    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}`);
        break;
      }
    }

    return {
      success: true,
      action: "agent_flow",
      goal,
      steps: log
    };

  } catch (error) {
    return {
      success: false,
      error: error.message,
      steps: log
    };
  }
};
