import { fetchQuoteSummary } from '../services/fundamentalsService.js';

const DEFAULT_HEADERS = {
  'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
  'Accept': 'application/json',
};

async function fetchHistory(symbol) {
  const url = `https://query1.finance.yahoo.com/v8/finance/chart/${symbol}?range=2y&interval=1d`;
  try {
    const res = await fetch(url, { headers: DEFAULT_HEADERS });
    if (!res.ok) return null;
    const data = await res.json();
    const result = data?.chart?.result?.[0];
    if (!result) return null;
    return result.indicators?.quote?.[0]?.close || [];
  } catch (e) {
    return null;
  }
}

function momentum12_1(closes) {
  if (!closes || closes.length < 252) return null;
  const n = closes.length;
  // 12-1 month: close[-21] / close[-252] - 1
  const current = closes[n - 21];
  const past = closes[n - 252];
  if (!current || !past) return null;
  return (current / past) - 1;
}

function realizedVol252(closes) {
  if (!closes || closes.length < 252) return null;
  const n = closes.length;
  const returns = [];
  for (let i = n - 251; i < n; i++) {
    const prev = closes[i - 1];
    const cur = closes[i];
    if (prev && cur) returns.push((cur - prev) / prev);
  }
  if (returns.length < 200) return null;
  
  const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
  const variance = returns.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / (returns.length - 1);
  // Annualize daily vol
  return Math.sqrt(variance) * Math.sqrt(252);
}

export async function pullRawRecord(ticker, asOf = new Date().toISOString().split('T')[0]) {
  const info = await fetchQuoteSummary(ticker);
  if (!info) return null;
  
  const closes = await fetchHistory(ticker);

  return {
    snapshot_date: asOf,
    ticker,
    price: info.price,
    marketCap: info.market_cap,
    
    // raw inputs
    trailingPE: info.pe_ttm,
    priceToBook: info.price_to_book,
    priceToSales: info.price_to_sales,
    freeCashflow: info.free_cash_flow,
    returnOnEquity: info.return_on_equity,
    grossMargins: info.gross_margins,
    debtToEquity: info.debt_to_equity,
    
    mom_12_1: momentum12_1(closes),
    realizedVol252: realizedVol252(closes),
    
    fundamentals_period_end: info.fiscal_end
  };
}
