/**
 * Runner: Phase 6.5 — Meta Reflection & Self-Rewrite
 */
import { detectMetaPatterns } from '../meta/reflection_core';
import { generateBlueprints } from '../meta/blueprint_generator';
import { validateRewrites } from '../meta/rewrite_validator';
import { applyBlueprints } from '../meta/apply_blueprints';
import { MetaConfig } from '../../config/meta.config';

(async () => {
  console.log('🧠 Running Meta-Reflection...');
  const patterns = detectMetaPatterns();
  console.table(patterns);

  // Normalize direction
  const normalizedPatterns = patterns.map((p) => ({
    ...p,
    direction: p.direction === 'positive' ? 'positive' : 'negative',
  })) as {
    policyId: string;
    avgCorrelation: number;
    volatility: number;
    support: number;
    direction: 'positive' | 'negative';
  }[];

  // Generate blueprints
  const blueprints = generateBlueprints(normalizedPatterns);
  console.log('—— Generated Blueprints ——');
  console.table(blueprints);

  // Normalize mutation
  const normalizedBlueprints = blueprints.map((b) => ({
    ...b,
    mutation: b.mutation === 'expand' ? 'expand' : 'contract',
  })) as {
    policyId: string;
    baseCorrelation: number;
    volatility: number;
    support: number;
    mutation: 'expand' | 'contract';
    version: number;
    rationale: string;
  }[];

  // Validate rewrites
  const plan = validateRewrites(normalizedBlueprints);
  console.log('—— Validation Plan ——');
  console.table(plan);

  // Normalize action field to union-safe type
  const normalizedPlan = plan.map((p) => ({
    ...p,
    action:
      p.action === 'increase_weight_gradually'
        ? 'increase_weight_gradually'
        : p.action === 'decrease_weight_or_monitor'
        ? 'decrease_weight_or_monitor'
        : 'none',
  })) as {
    policyId: string;
    version: number;
    valid: boolean;
    reason: string;
    action: 'none' | 'increase_weight_gradually' | 'decrease_weight_or_monitor';
  }[];

  // Dry-run apply first
  const dryRes = applyBlueprints(normalizedPlan, { dryRun: true, step: 0.05 });
  console.log('—— Dry-Run Updates ——');
  console.table(dryRes.updates);

  // Real apply
  const realRes = applyBlueprints(normalizedPlan, { dryRun: false, step: 0.05 });
  console.log('—— REAL Updates ——');
  console.table(realRes.updates);

  console.log(`✅ Meta-Reflection complete (dryRun=${MetaConfig.dryRunByDefault}).`);
})();
