import fs from 'fs';
import path from 'path';
import { ab } from './ab';
import { randomDelay } from './anti-detection';

const AUTH_STATE_PATH = path.join(process.env.HOME || '~', '.clawdbot/workspace/reonomy-auth.json');
const DEFAULT_EMAIL = process.env.REONOMY_EMAIL || 'henry@realestateenhanced.com';
const DEFAULT_PASSWORD = process.env.REONOMY_PASSWORD || '9082166532';

/**
 * Check if we have a valid session by loading saved state and testing it
 */
export async function hasValidSession(): Promise<boolean> {
  if (!fs.existsSync(AUTH_STATE_PATH)) return false;

  ab(`state load "${AUTH_STATE_PATH}"`);
  ab('open "https://app.reonomy.com/#!/home"');
  await randomDelay(4000, 6000);

  const urlCheck = ab('eval "window.location.href"');
  if (
    urlCheck.output?.includes('app.reonomy.com') &&
    !urlCheck.output?.includes('auth.reonomy.com') &&
    !urlCheck.output?.includes('login')
  ) {
    return true;
  }
  return false;
}

/**
 * Login to Reonomy. Fills email/password, clicks Log In, saves state.
 */
export async function login(
  email: string = DEFAULT_EMAIL,
  password: string = DEFAULT_PASSWORD
): Promise<boolean> {
  ab('open "https://app.reonomy.com/#!/login"');
  await randomDelay(3000, 5000);

  const snapshot = ab('snapshot -i');
  if (!snapshot.output?.includes('textbox "Email"')) {
    // Maybe already logged in
    const urlCheck = ab('eval "window.location.href"');
    if (urlCheck.output?.includes('app.reonomy.com') && !urlCheck.output?.includes('login')) {
      return true;
    }
    throw new Error('Login form not found');
  }

  const emailMatch = snapshot.output.match(/textbox "Email" \[ref=(e\d+)\]/);
  const passMatch = snapshot.output.match(/textbox "Password" \[ref=(e\d+)\]/);
  const loginMatch = snapshot.output.match(/button "Log In" \[ref=(e\d+)\]/);

  if (!emailMatch || !passMatch || !loginMatch) {
    throw new Error('Could not find login form elements');
  }

  ab(`fill @${emailMatch[1]} "${email}"`);
  await randomDelay(800, 1500);
  ab(`fill @${passMatch[1]} "${password}"`);
  await randomDelay(800, 1500);

  ab(`click @${loginMatch[1]}`);
  await randomDelay(12000, 16000);

  const postLoginUrl = ab('eval "window.location.href"');
  if (postLoginUrl.output?.includes('auth.reonomy.com') || postLoginUrl.output?.includes('login')) {
    throw new Error('Login failed - still on login page');
  }

  // Save session state
  ab(`state save "${AUTH_STATE_PATH}"`);
  return true;
}

/**
 * Ensure we're authenticated — try saved session first, login if needed
 */
export async function ensureAuth(): Promise<void> {
  const valid = await hasValidSession();
  if (valid) return;
  await login();
}
