import { SalesRecord } from '../../types';
import { ab } from '../ab';
import { randomDelay } from '../anti-detection';

/**
 * Extract sales history from the Sales tab.
 */
export async function extractSales(): Promise<SalesRecord[]> {
  // Click Sales tab
  ab('find role tab click --name "Sales"');
  await randomDelay(3000, 5000);

  const snap = ab('snapshot -i');
  return parseSalesFromSnapshot(snap.output || '');
}

export function parseSalesFromSnapshot(snapshot: string): SalesRecord[] {
  if (!snapshot) return [];

  const records: SalesRecord[] = [];
  const text = snapshot;

  // Sale records typically appear in sections with buyer/seller/price/date
  // Pattern varies but we look for key labels followed by values

  // Try to find sale record blocks
  const saleBlocks = text.split(/(?=Sale Date|Recording Date|Document Date)/i);

  for (const block of saleBlocks) {
    if (block.length < 20) continue;

    const record: SalesRecord = {};

    // Buyer
    const buyerMatch = block.match(/(?:Buyer|Grantee)[:\s]*([^\n]+)/i);
    if (buyerMatch) record.buyer = buyerMatch[1].trim();

    // Seller
    const sellerMatch = block.match(/(?:Seller|Grantor)[:\s]*([^\n]+)/i);
    if (sellerMatch) record.seller = sellerMatch[1].trim();

    // Sale Date
    const dateMatch = block.match(/(?:Sale Date|Recording Date|Document Date)[:\s]*([^\n]+)/i);
    if (dateMatch) record.saleDate = dateMatch[1].trim();

    // Price
    const priceMatch = block.match(/(?:Sale Price|Price|Amount)[:\s]*\$?([\d,]+)/i);
    if (priceMatch) record.price = priceMatch[1].replace(/,/g, '');

    // Deed Type
    const deedMatch = block.match(/(?:Deed Type|Document Type|Deed)[:\s]*([^\n]+)/i);
    if (deedMatch) record.deedType = deedMatch[1].trim();

    // Only add if we found at least one useful field
    if (record.buyer || record.seller || record.saleDate || record.price) {
      records.push(record);
    }
  }

  return records;
}
