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

/**
 * Extract Building & Lot data from the property page.
 * This is typically the default tab when you open a property.
 */
export async function extractBuilding(): Promise<BuildingData> {
  const snap = ab('snapshot -i');
  const text = snap.output || '';
  const data: BuildingData = {};

  // Stories
  const storiesMatch = text.match(/(?:Stories|Floors|Number of Stories)[:\s]*(\d+)/i);
  if (storiesMatch) data.stories = storiesMatch[1];

  // Number of buildings
  const buildingsMatch = text.match(/(?:Buildings|Number of Buildings)[:\s]*(\d+)/i);
  if (buildingsMatch) data.buildings = buildingsMatch[1];

  // Units
  const unitsMatch = text.match(/(\d+)\s*Unit/i);
  if (unitsMatch) data.units = unitsMatch[1];

  // Building Area / Square Footage
  const areaMatch = text.match(/(\d[\d,]*(?:\.\d+)?)\s*(?:SF|Sq\.?\s*Ft)/i);
  if (areaMatch) data.buildingArea = areaMatch[1].replace(/,/g, '');

  // Property Type
  const typeMatch = text.match(/(?:Property Type|Type)[:\s]*([A-Za-z\s()]+?)(?:\n|$)/i);
  if (typeMatch) data.propertyType = typeMatch[1].trim();

  // Lot Size
  const lotAcresMatch = text.match(/([\d,.]+)\s*Acre/i);
  if (lotAcresMatch) {
    data.lotSize = lotAcresMatch[1] + ' Acres';
  } else {
    const lotSfMatch = text.match(/(?:Lot Size)[:\s]*([\d,]+)\s*(?:SF|Sq)/i);
    if (lotSfMatch) data.lotSize = lotSfMatch[1].replace(/,/g, '') + ' SF';
  }

  // Zoning
  const zoningMatch = text.match(/(?:Zoning)[:\s]*([A-Z0-9][\w\-]*)/i);
  if (zoningMatch) data.zoning = zoningMatch[1];

  // Year Built
  const yearMatch = text.match(/(?:Year Built|Built)[:\s]*(\d{4})/i);
  if (yearMatch) data.yearBuilt = yearMatch[1];

  // Opportunity Zone
  if (/opportunity zone/i.test(text)) {
    const ozMatch = text.match(/(?:Opportunity Zone)[:\s]*(Yes|No|True|False)/i);
    data.opportunityZone = ozMatch ? ozMatch[1] : 'Yes';
  }

  // MSA
  const msaMatch = text.match(/(?:MSA|Metropolitan)[:\s]*([^\n]+)/i);
  if (msaMatch) data.msa = msaMatch[1].trim();

  // County
  const countyMatch = text.match(/(?:County)[:\s]*([^\n]+)/i);
  if (countyMatch) data.county = countyMatch[1].trim();

  // Legal Description
  const legalMatch = text.match(/(?:Legal Description|Legal)[:\s]*([^\n]+)/i);
  if (legalMatch) data.legal = legalMatch[1].trim();

  return data;
}
