// In a real setup, this data would be loaded from Sharadar/Compustat.
// For testing, we allow an injected dataset.

let globalFundamentalsBySymbol = new Map(); 

export function loadFundamentals(data) {
  globalFundamentalsBySymbol.clear();
  // Group by symbol
  for (const record of data) {
    if (!globalFundamentalsBySymbol.has(record.symbol)) {
      globalFundamentalsBySymbol.set(record.symbol, []);
    }
    globalFundamentalsBySymbol.get(record.symbol).push(record);
  }

  // Sort each group by datekey ascending
  for (const [sym, records] of globalFundamentalsBySymbol.entries()) {
    records.sort((a, b) => new Date(a.datekey) - new Date(b.datekey));
  }
}

export function getFundamentalsAsOf(symbol, dateStr) {
  const targetDate = new Date(dateStr);
  const records = globalFundamentalsBySymbol.get(symbol);
  if (!records) return null;
  
  // Find the most recent fundamental report where filing date <= targetDate
  let latest = null;
  for (const record of records) {
    
    // GUARDRAIL: We absolutely require a filing date (datekey).
    // If datekey <= targetDate, it's safe.
    // If datekey is missing, fallback to fiscalEnd + 4 months (120 days).
    let isAvailable = false;
    if (record.datekey) {
      if (new Date(record.datekey) <= targetDate) isAvailable = true;
    } else if (record.fiscalEnd) {
      const safeReleaseDate = new Date(record.fiscalEnd);
      safeReleaseDate.setDate(safeReleaseDate.getDate() + 120); // Add 4 months roughly
      if (safeReleaseDate <= targetDate) isAvailable = true;
    } else {
      throw new Error(`Record for ${symbol} lacks both datekey and fiscalEnd. Unsafe.`);
    }

    if (isAvailable) {
      latest = record;
    } else {
      if (record.datekey && new Date(record.datekey) > targetDate) break;
    }
  }

  return latest ? latest.metrics : null;
}
