import fs from 'fs';
import path from 'path';
import { ab } from './ab';

const DAILY_STATS_PATH = path.join(process.env.HOME || '~', '.clawdbot/workspace/reonomy-daily-stats.json');
const MAX_DAILY_PROPERTIES = parseInt(process.env.MAX_DAILY_PROPERTIES || '50');

// ── Random Delays ──

export function randomDelay(minMs: number, maxMs: number): Promise<void> {
  const delay = Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
  return new Promise((resolve) => setTimeout(resolve, delay));
}

// ── Shuffle (Fisher-Yates) ──

export function shuffle<T>(array: T[]): T[] {
  const arr = [...array];
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}

// ── Humanize: occasional random "human" actions ──

export async function humanize(): Promise<void> {
  const actions = [
    () => ab('scroll down 200', { verbose: false }),
    () => ab('scroll up 100', { verbose: false }),
    () => randomDelay(500, 1500),
    () => randomDelay(1000, 2000),
  ];

  // 30% chance to do a random action
  if (Math.random() < 0.3) {
    const action = actions[Math.floor(Math.random() * actions.length)];
    await action();
  }
}

// ── Daily Limit Tracking ──

export interface DailyStats {
  date: string;
  propertiesScraped: number;
  leadsFound: number;
}

export function getDailyStats(): DailyStats {
  const today = new Date().toISOString().split('T')[0];
  try {
    const data = JSON.parse(fs.readFileSync(DAILY_STATS_PATH, 'utf8'));
    if (data.date === today) return data;
  } catch {}
  return { date: today, propertiesScraped: 0, leadsFound: 0 };
}

export function saveDailyStats(stats: DailyStats): void {
  fs.writeFileSync(DAILY_STATS_PATH, JSON.stringify(stats, null, 2));
}

export function getRemainingToday(): number {
  const stats = getDailyStats();
  return Math.max(0, MAX_DAILY_PROPERTIES - stats.propertiesScraped);
}

export function isDailyLimitReached(): boolean {
  return getRemainingToday() <= 0;
}

/**
 * Dismiss any Reonomy notification banners ("Let's Go" popups)
 */
export async function dismissBanners(): Promise<void> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const snap = ab('snapshot -i', { verbose: false });
    const letsGoMatch = snap.output?.match(/button "Let's Go" \[ref=(e\d+)\]/);
    if (!letsGoMatch) break;
    ab(`click @${letsGoMatch[1]}`);
    await randomDelay(800, 1500);
  }
}
