#!/usr/bin/env node

/**
 * Simple Reonomy Explorer
 * Step-by-step exploration with error handling
 */

const puppeteer = require('puppeteer');
const fs = require('fs');

const REONOMY_EMAIL = process.env.REONOMY_EMAIL || 'henry@realestateenhanced.com';
const REONOMY_PASSWORD = process.env.REONOMY_PASSWORD || '9082166532';

async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function explore() {
  console.log('🚀 Starting Reonomy Explorer...\n');

  const browser = await puppeteer.launch({
    headless: false, // Keep visible
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--window-size=1920,1080']
  });

  const page = await browser.newPage();
  await page.setViewport({ width: 1920, height: 1080 });

  try {
    // Step 1: Navigate to login
    console.log('📍 Step 1: Navigating to login...');
    await page.goto('https://app.reonomy.com/#!/account', { waitUntil: 'domcontentloaded', timeout: 60000 });
    await sleep(3000);
    console.log('✅ Page loaded');

    // Step 2: Fill credentials
    console.log('📍 Step 2: Filling credentials...');
    const emailInput = await page.waitForSelector('input[type="email"]', { timeout: 10000 });
    await emailInput.click();
    await emailInput.type(REONOMY_EMAIL, { delay: 100 });

    const passInput = await page.waitForSelector('input[type="password"]', { timeout: 10000 });
    await passInput.click();
    await passInput.type(REONOMY_PASSWORD, { delay: 100 });
    console.log('✅ Credentials filled');

    // Step 3: Submit login
    console.log('📍 Step 3: Submitting login...');
    await page.click('button[type="submit"]');
    console.log('⏳ Waiting for redirect...');

    // Wait for navigation - Reonomy redirects through Auth0
    await sleep(8000);

    // Step 4: Check current state
    const url = page.url();
    console.log(`\n📍 Current URL: ${url}`);

    if (url.includes('auth.reonomy.com') || url.includes('login')) {
      console.log('⚠️  Still on login page. Checking for errors...');
      const pageText = await page.evaluate(() => document.body.innerText);
      console.log('Page text:', pageText.substring(0, 500));
    } else {
      console.log('✅ Successfully logged in!');

      // Wait for dashboard to load
      await sleep(5000);

      // Step 5: Take screenshot
      console.log('\n📍 Step 5: Capturing dashboard...');
      try {
        await page.screenshot({ path: '/tmp/reonomy-dashboard.png' });
        console.log('✅ Screenshot saved: /tmp/reonomy-dashboard.png');
      } catch (err) {
        console.log('⚠️  Screenshot failed:', err.message);
      }

      // Step 6: Extract links
      console.log('\n📍 Step 6: Finding navigation links...');
      const links = await page.evaluate(() => {
        const allLinks = Array.from(document.querySelectorAll('a[href]'));
        return allLinks
          .map(a => ({
            text: (a.innerText || a.textContent).trim(),
            href: a.href
          }))
          .filter(l => l.text && l.text.length > 0 && l.text.length < 100)
          .slice(0, 30);
      });

      console.log(`Found ${links.length} links:`);
      links.forEach((l, i) => {
        console.log(`  ${i + 1}. "${l.text}" -> ${l.href.substring(0, 60)}...`);
      });

      // Save links
      fs.writeFileSync('/tmp/reonomy-links.json', JSON.stringify(links, null, 2));

      // Step 7: Look for property/owner information
      console.log('\n📍 Step 7: Looking for data elements...');
      const pageText = await page.evaluate(() => document.body.innerText);
      fs.writeFileSync('/tmp/reonomy-text.txt', pageText);

      // Check for common property-related keywords
      const keywords = ['search', 'property', 'owner', 'building', 'address', 'lead', 'contact'];
      const foundKeywords = [];
      keywords.forEach(kw => {
        if (pageText.toLowerCase().includes(kw)) {
          foundKeywords.push(kw);
        }
      });

      console.log(`Found keywords: ${foundKeywords.join(', ')}`);

      // Step 8: Look for input fields
      const inputs = await page.evaluate(() => {
        return Array.from(document.querySelectorAll('input'))
          .map(i => ({
            type: i.type,
            placeholder: i.placeholder,
            name: i.name
          }))
          .filter(i => i.placeholder)
          .slice(0, 20);
      });

      console.log('\nInput fields found:');
      inputs.forEach((inp, i) => {
        console.log(`  ${i + 1}. Type: ${inp.type}, Placeholder: "${inp.placeholder}"`);
      });
    }

    console.log('\n✅ Exploration complete!');
    console.log('📸 Saved files:');
    console.log('   - /tmp/reonomy-dashboard.png');
    console.log('   - /tmp/reonomy-text.txt');
    console.log('   - /tmp/reonomy-links.json');
    console.log('\n⏸️  Press Ctrl+C to close browser (keeping open for manual inspection)...');

    // Keep browser open
    await new Promise(() => {});

  } catch (error) {
    console.error('\n❌ Error:', error.message);
    console.error(error.stack);
  } finally {
    await browser.close();
  }
}

explore().catch(error => {
  console.error('Fatal error:', error);
  process.exit(1);
});
