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

/**
 * Extract debt/mortgage info from the Debt tab.
 */
export async function extractDebt(): Promise<DebtRecord[]> {
  // Click Debt tab
  ab('find role tab click --name "Debt"');
  await randomDelay(3000, 5000);

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

export function parseDebtFromSnapshot(snapshot: string): DebtRecord[] {
  if (!snapshot) return [];

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

  // Split by mortgage/loan blocks
  const debtBlocks = text.split(/(?=Lender|Mortgage|Loan\s+Type)/i);

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

    const record: DebtRecord = {};

    // Lender
    const lenderMatch = block.match(/(?:Lender)[:\s]*([^\n]+)/i);
    if (lenderMatch) record.lender = lenderMatch[1].trim();

    // Loan Type
    const loanTypeMatch = block.match(/(?:Loan Type)[:\s]*([^\n]+)/i);
    if (loanTypeMatch) record.loanType = loanTypeMatch[1].trim();

    // Mortgage Type
    const mortgageMatch = block.match(/(?:Mortgage Type|Type)[:\s]*([^\n]+)/i);
    if (mortgageMatch && !record.loanType) record.mortgageType = mortgageMatch[1].trim();

    // Borrower
    const borrowerMatch = block.match(/(?:Borrower)[:\s]*([^\n]+)/i);
    if (borrowerMatch) record.borrower = borrowerMatch[1].trim();

    // Amount
    const amountMatch = block.match(/(?:Amount|Loan Amount|Mortgage Amount)[:\s]*\$?([\d,]+)/i);
    if (amountMatch) record.amount = amountMatch[1].replace(/,/g, '');

    // Origination Date
    const origMatch = block.match(/(?:Origination|Origination Date)[:\s]*([^\n]+)/i);
    if (origMatch) record.originationDate = origMatch[1].trim();

    // Maturity Date
    const maturityMatch = block.match(/(?:Maturity|Maturity Date)[:\s]*([^\n]+)/i);
    if (maturityMatch) record.maturityDate = maturityMatch[1].trim();

    // Only add if we found at least one useful field
    if (record.lender || record.borrower || record.amount || record.loanType) {
      records.push(record);
    }
  }

  return records;
}
