import { buildFactorProfiles } from '../descriptiveLens.js';

test('strictly-better stock ranks higher on every factor', async () => {
  const good = {
    ticker: 'GOOD',
    trailingPE: 8,
    priceToBook: 1,
    priceToSales: 0.5,
    freeCashflow: 1e10,
    marketCap: 1e11,
    returnOnEquity: 0.30,
    grossMargins: 0.60,
    debtToEquity: 10,
    mom_12_1: 0.25,
    realizedVol252: 0.15
  };

  const bad = {
    ticker: 'BAD',
    trailingPE: 50,
    priceToBook: 10,
    priceToSales: 12,
    freeCashflow: 1e8,
    marketCap: 1e11,
    returnOnEquity: 0.02,
    grossMargins: 0.10,
    debtToEquity: 300,
    mom_12_1: -0.10,
    realizedVol252: 0.60
  };

  // buildFactorProfiles supports injecting a universe payload directly for testing
  const out = await buildFactorProfiles([good, bad]);

  // 'out' returns a map { 'GOOD': { ... }, 'BAD': { ... } } during test injection
  
  for (const f of ['value', 'quality', 'lowVol', 'momentum', 'composite']) {
    // A strictly better stock MUST have a higher percentile rank
    if (out['GOOD'][f] <= out['BAD'][f]) {
      throw new Error(`Sign catastrophe: GOOD ranked ${out['GOOD'][f]} on ${f}, but BAD ranked ${out['BAD'][f]}. GOOD must strictly outrank BAD.`);
    }
  }

  console.log("PASS: Orientation logic correctly handles signs. 'Higher percentile' always means 'more favorable'.");
});

// Jest polyfill for simple node execution
function test(name, fn) {
  console.log(`Running test: ${name}`);
  fn().catch(e => {
    console.error(`FAIL: ${e.message}`);
    process.exit(1);
  });
}
