#!/usr/bin/env node
/**
 * Reonomy Quick Demo - Single contact extraction
 * Shows the full flow in ~60 seconds
 * 
 * Usage: node reonomy-quick-demo.js
 * Or: buba reonomy demo
 */

const { execSync } = require('child_process');

const EMAIL = process.env.REONOMY_EMAIL || 'henry@realestateenhanced.com';
const PASSWORD = process.env.REONOMY_PASSWORD || '9082166532';
const SEARCH_ID = process.env.REONOMY_SEARCH_ID || 'bacfd104-fed5-4cc4-aba1-933f899de3f8';

function ab(cmd) {
  console.log(`  → ${cmd}`);
  try {
    return execSync(`agent-browser ${cmd}`, { encoding: 'utf8', timeout: 30000 }).trim();
  } catch (e) {
    console.log(`  ⚠️ ${e.message.substring(0, 50)}`);
    return null;
  }
}

function wait(ms) {
  return new Promise(r => setTimeout(r, ms));
}

async function demo() {
  console.log('\n🎯 REONOMY CONTACT EXTRACTION DEMO');
  console.log('===================================\n');
  
  // Login
  console.log('📍 Step 1: Login');
  ab('open "https://app.reonomy.com/#!/login" --headed');
  await wait(4000);
  ab(`fill @e2 "${EMAIL}"`);
  await wait(500);
  ab(`fill @e3 "${PASSWORD}"`);
  await wait(500);
  ab('click @e5');
  console.log('  ⏳ Logging in...');
  await wait(12000);
  
  // Search
  console.log('\n📍 Step 2: Load filtered search');
  ab(`open "https://app.reonomy.com/#!/search/${SEARCH_ID}"`);
  await wait(8000);
  
  // Click property
  console.log('\n📍 Step 3: Select property');
  const snap1 = ab('snapshot -i');
  const propMatch = snap1?.match(/button "(\d+[^"]+)" \[ref=(e\d+)\]/);
  if (propMatch) {
    console.log(`  Property: ${propMatch[1].substring(0, 50)}...`);
    ab(`click @${propMatch[2]}`);
  } else {
    ab('click @e8');
  }
  await wait(6000);
  
  // Owner tab
  console.log('\n📍 Step 4: Owner tab');
  ab('find role tab click --name "Owner"');
  await wait(5000);
  
  // View Contacts
  console.log('\n📍 Step 5: View Contacts');
  const snap2 = ab('snapshot -i');
  const vcMatch = snap2?.match(/button "View Contacts[^"]*" \[ref=(e\d+)\]/);
  if (vcMatch) {
    ab(`click @${vcMatch[1]}`);
    await wait(5000);
  }
  
  // Find person
  console.log('\n📍 Step 6: Navigate to person');
  const snap3 = ab('snapshot');
  const personMatch = snap3?.match(/\/url: \/!\/person\/([a-f0-9-]+)/);
  if (personMatch) {
    ab(`open "https://app.reonomy.com/!/person/${personMatch[1]}"`);
    await wait(6000);
  }
  
  // Click Contact
  console.log('\n📍 Step 7: Open contact modal');
  const snap4 = ab('snapshot -i');
  const contactMatch = snap4?.match(/button "Contact" \[ref=(e\d+)\]/);
  if (contactMatch) {
    ab(`click @${contactMatch[1]}`);
    await wait(3000);
  }
  
  // Extract
  console.log('\n📍 Step 8: EXTRACT CONTACTS');
  const snap5 = ab('snapshot -i');
  
  console.log('\n🎉 CONTACTS FOUND:');
  console.log('==================');
  
  // Phones
  const phones = snap5?.matchAll(/button "(\d{3}-\d{3}-\d{4})\s+([^"]+)"/g) || [];
  for (const p of phones) {
    console.log(`  📞 ${p[1]} (${p[2].substring(0, 30)})`);
  }
  
  // Emails  
  const emails = snap5?.matchAll(/button "([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})"/g) || [];
  for (const e of emails) {
    console.log(`  📧 ${e[1]}`);
  }
  
  // Screenshot
  ab('screenshot /tmp/reonomy-demo-final.png');
  console.log('\n📸 Screenshot: /tmp/reonomy-demo-final.png');
  
  console.log('\n✅ Demo complete! Browser left open.');
  console.log('   Run: agent-browser close');
}

demo().catch(e => {
  console.error('Demo failed:', e.message);
  process.exit(1);
});
