const debugBase = 'http://127.0.0.1:9222';
const appUrl = 'http://10.0.2.2:8080/mikrotik/admin/subscribers.php?ua_android=1';
const password = process.env.QA_PASSWORD || '';
const promptOnly = process.argv.includes('--prompt-only');
if (!password && !promptOnly) throw new Error('QA_PASSWORD is required');

const targets = await fetch(`${debugBase}/json`).then(response => response.json());
const page = targets.find(target => target.type === 'page');
if (!page) throw new Error('Android WebView target was not found');
const socket = new WebSocket(page.webSocketDebuggerUrl);
await new Promise((resolve, reject) => {
  socket.addEventListener('open', resolve, {once:true});
  socket.addEventListener('error', reject, {once:true});
});

let id = 0;
const pending = new Map();
socket.addEventListener('message', event => {
  const message = JSON.parse(event.data);
  if (!message.id || !pending.has(message.id)) return;
  const request = pending.get(message.id);
  pending.delete(message.id);
  message.error ? request.reject(new Error(message.error.message)) : request.resolve(message.result);
});
function send(method, params={}) {
  const commandId = ++id;
  socket.send(JSON.stringify({id:commandId, method, params}));
  return new Promise((resolve,reject) => pending.set(commandId,{resolve,reject}));
}
async function evaluate(expression) {
  const response = await send('Runtime.evaluate',{expression,awaitPromise:true,returnByValue:true});
  if (response.exceptionDetails) {
    throw new Error(response.result?.description || response.exceptionDetails.exception?.description || response.exceptionDetails.text);
  }
  return response.result.value;
}
const delay = milliseconds => new Promise(resolve => setTimeout(resolve,milliseconds));
const visible = selector => `(() => { const el=document.querySelector(${JSON.stringify(selector)}); return !!el && getComputedStyle(el).display !== 'none'; })()`;

await send('Page.enable');
await send('Runtime.enable');
await send('Page.navigate',{url:appUrl});
await delay(1600);

await evaluate(`(() => {
  const link=document.querySelector('a[href*="subscribers_view.php"]');
  if(!link) throw new Error('Protected subscriber view button was not found');
  link.click(); return true;
})()`);
await delay(250);
const firstPrompt = await evaluate(`(() => ({
  visible: ${visible('#uaAndroidProtectedAuth')},
  title: document.querySelector('#uaAndroidProtectedTitle')?.textContent?.trim() || '',
  error: document.querySelector('.ua-android-protected-error')?.textContent?.trim() || '',
  href: location.href
}))()`);
if (promptOnly) {
  socket.close();
  console.log(JSON.stringify({firstPrompt},null,2));
  process.exit(0);
}

await evaluate(`(() => {
  const input=document.querySelector('#uaAndroidProtectedPassword'), form=document.querySelector('#uaAndroidProtectedForm');
  if(!input||!form) throw new Error('Password prompt was not mounted');
  input.value=${JSON.stringify(password)};
  input.dispatchEvent(new Event('input',{bubbles:true}));
  form.requestSubmit(); return true;
})()`);
await delay(2200);
const viewOpened = await evaluate(`(() => ({
  href: location.href,
  title: document.title,
  hasEdit: !!document.querySelector('a[href*="subscribers_edit.php"]'),
  authVisible: ${visible('#uaAndroidProtectedAuth')},
  errorText: /انتهت جلسة الحماية|لم يتم إدخال كلمة المرور|رابط الحماية غير صالح/.test(document.body.innerText)
}))()`);

await evaluate(`(() => {
  const link=document.querySelector('a[href*="subscribers_edit.php"]');
  if(!link) throw new Error('Nested protected edit button was not found');
  link.click(); return true;
})()`);
await delay(300);
const nestedPrompt = await evaluate(`(() => ({
  visible: ${visible('#uaAndroidProtectedAuth')},
  title: document.querySelector('#uaAndroidProtectedTitle')?.textContent?.trim() || '',
  error: document.querySelector('.ua-android-protected-error')?.textContent?.trim() || '',
  href: location.href
}))()`);

await evaluate(`(() => {
  const input=document.querySelector('#uaAndroidProtectedPassword'), form=document.querySelector('#uaAndroidProtectedForm');
  input.value=${JSON.stringify(password)};
  input.dispatchEvent(new Event('input',{bubbles:true}));
  form.requestSubmit(); return true;
})()`);
await delay(2200);
const continued = await evaluate(`(() => ({
  href: location.href,
  title: document.title,
  authVisible: ${visible('#uaAndroidProtectedAuth')},
  errorText: /انتهت جلسة الحماية|لم يتم إدخال كلمة المرور|رابط الحماية غير صالح/.test(document.body.innerText),
  text: document.body.innerText.trim().slice(0,180)
}))()`);

socket.close();
const result={firstPrompt,viewOpened,nestedPrompt,continued};
console.log(JSON.stringify(result,null,2));
if (!firstPrompt.visible || !viewOpened.href.includes('subscribers_view.php') || !viewOpened.hasEdit || viewOpened.authVisible || viewOpened.errorText || !nestedPrompt.visible || !continued.href.includes('subscribers_edit.php') || continued.authVisible || continued.errorText) {
  process.exitCode=1;
}
