// tests/phase8/responsive_policy_enhanced.spec.ts
import { describe, it, expect, vi } from 'vitest';
import { policyManager } from '@/lib/core/policies';
import { logPolicyApplied } from '@/lib/telemetry/policy.telemetry';
import { readEvolutionReport } from '@/lib/telemetry/evolution.telemetry';
import { appendEvolutionSnapshot, readEvolutionHistory } from '@/lib/evolution/history.collector';

describe('🧩 Phase 8.9 — Responsive Policy Enhanced & History Collector', () => {
  it('stores and reuses context cache for device', () => {
    // simulate first run
    vi.spyOn(window, 'innerWidth', 'get').mockReturnValue(420);
    const p1 = policyManager.compute();
    expect(p1.device).toBe('mobile');
    // simulate stored
    const storedDevice = sessionStorage.getItem('DEVICE_KIND');
    expect(storedDevice).toBe('mobile');

    // recompute without passing device
    const p2 = policyManager.compute();
    expect(p2.device).toBe(storedDevice);
  });

  it('adds confidence meta field to policy', () => {
    const p = policyManager.compute('desktop');
    expect(p.meta).toBeDefined();
    expect(p.meta?.confidence).toBeGreaterThanOrEqual(0.8);
  });

  it('logs policy into Evolution Report via unified telemetry', () => {
    const p = policyManager.compute('tablet');
    logPolicyApplied(p);
    const report = readEvolutionReport();
    expect(report.lastContext?.device).toBe('tablet');
    expect(typeof report.lastContext?.confidence).toBe('number');
  });

  it('appends evolution snapshot to history', () => {
    const snapshot = appendEvolutionSnapshot();
    expect(snapshot).toBeTruthy();
    const history = readEvolutionHistory();
    expect(Array.isArray(history)).toBe(true);
    expect(history.at(-1)?.device).toBe(snapshot.device);
  });
});
