import { rectForLabel } from './ios-source.mjs';

const [bundleId, label] = process.argv.slice(2);
if (!bundleId || !label) throw new Error('Usage: node scripts/tap-ios-label.mjs <bundleId> <label>');
const base = `http://${process.env.WDA_HOST || 'localhost'}:${process.env.WDA_PORT || '8100'}`;
async function request(path, method = 'GET', body) {
  const response = await fetch(`${base}${path}`, {
    method,
    headers: body ? { 'content-type': 'application/json' } : undefined,
    body: body ? JSON.stringify(body) : undefined,
  });
  const payload = await response.json();
  if (!response.ok || payload.value?.error) throw new Error(payload.value?.message || String(response.status));
  return payload.value;
}
const session = await request('/session', 'POST', { capabilities: { alwaysMatch: { platformName: 'iOS', automationName: 'XCUITest' } } });
const sessionId = session.sessionId || session.capabilities?.sessionId;
const prefix = `/session/${sessionId}`;
try {
  await request(`${prefix}/wda/apps/launch`, 'POST', { bundleId });
  const xml = await request(`${prefix}/source`);
  const rect = rectForLabel(xml, label);
  if (!rect) throw new Error(`Label not found: ${label}`);
  await request(`${prefix}/wda/tap`, 'POST', { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 });
  await new Promise((resolve) => setTimeout(resolve, 1500));
  const afterXml = await request(`${prefix}/source`);
  const labels = [...afterXml.matchAll(/<XCUIElementType(?:Button|StaticText)[^>]*?(?:name|label)="([^"]*)"[^>]*>/g)]
    .map((match) => match[1])
    .filter((value) => value && !value.includes('@'))
    .slice(0, 40);
  console.log(JSON.stringify({ tapped: label, labels }));
} finally {
  await request(prefix, 'DELETE').catch(() => {});
}
