import { afterEach, describe, expect, it, vi } from "vitest";

const PROBLEM_UNITS_FLAG = "FEATURE_ASSISTANT_PROBLEM_UNITS_V1";
const LIFECYCLE_RUNTIME_FLAG = "FEATURE_ASSISTANT_LIFECYCLE_RUNTIME_V1";
const ORIGINAL_PROBLEM_UNITS_FLAG = process.env[PROBLEM_UNITS_FLAG];
const ORIGINAL_LIFECYCLE_RUNTIME_FLAG = process.env[LIFECYCLE_RUNTIME_FLAG];

function restoreFlags(): void {
  if (ORIGINAL_PROBLEM_UNITS_FLAG === undefined) {
    delete process.env[PROBLEM_UNITS_FLAG];
  } else {
    process.env[PROBLEM_UNITS_FLAG] = ORIGINAL_PROBLEM_UNITS_FLAG;
  }

  if (ORIGINAL_LIFECYCLE_RUNTIME_FLAG === undefined) {
    delete process.env[LIFECYCLE_RUNTIME_FLAG];
  } else {
    process.env[LIFECYCLE_RUNTIME_FLAG] = ORIGINAL_LIFECYCLE_RUNTIME_FLAG;
  }
}

async function normalizeWithFlags(input: {
  problemUnitsFlag: "0" | "1";
  lifecycleRuntimeFlag: "0" | "1";
}) {
  process.env[PROBLEM_UNITS_FLAG] = input.problemUnitsFlag;
  process.env[LIFECYCLE_RUNTIME_FLAG] = input.lifecycleRuntimeFlag;
  vi.resetModules();
  const { normalizeRetrievalResult } = await import("../src/services/retrievalResultNormalizer");
  return normalizeRetrievalResult("F1", ["R1"], "hybrid_store_plus_live", {
    status: "ok",
    result_type: "list",
    items: [
      {
        source_entity: "Document",
        source_id: "DOC-1",
        risk_score: 4
      }
    ],
    summary: {
      broad_query_detected: false
    },
    evidence: [
      {
        evidence_id: "ev-1",
        claim_ref: "requirement:R1",
        source_type: "retrieval_item",
        pointer: {
          fragment_id: "F1",
          route: "hybrid_store_plus_live",
          source: {
            namespace: "snapshot_2020",
            entity: "Document",
            id: "DOC-1",
            period: "2020-06"
          },
          locator: {
            field_path: "risk_score",
            item_index: 0
          }
        },
        failed_expected_edge: "payment_to_settlement",
        anomaly_patterns: ["period_close_risk", "broken_lifecycle", "missing_link", "no_continuation"],
        confidence: "medium"
      }
    ],
    why_included: ["test"],
    selection_reason: ["test"],
    risk_factors: ["test"],
    business_interpretation: ["test"],
    confidence: "medium",
    limitations: [],
    errors: []
  });
}

describe.sequential("retrieval lifecycle runtime rollout", () => {
  afterEach(() => {
    restoreFlags();
    vi.resetModules();
  });

  it("keeps Stage 2 payload when lifecycle runtime flag is OFF", async () => {
    const result = await normalizeWithFlags({
      problemUnitsFlag: "1",
      lifecycleRuntimeFlag: "0"
    });
    expect(Array.isArray(result.problem_units)).toBe(true);
    const first = result.problem_units?.[0];
    expect(first?.lifecycle_domain).toBeUndefined();
    expect(first?.lifecycle_defect_type).toBeUndefined();
    expect(result.summary.lifecycle_enriched_units).toBe(0);
  });

  it("adds lifecycle fields to problem units when lifecycle runtime flag is ON", async () => {
    const result = await normalizeWithFlags({
      problemUnitsFlag: "1",
      lifecycleRuntimeFlag: "1"
    });

    expect(Array.isArray(result.problem_units)).toBe(true);
    expect(result.problem_units?.length).toBeGreaterThan(0);
    const first = result.problem_units?.[0];
    expect(first?.lifecycle_domain).toBeTruthy();
    expect(first?.current_lifecycle_state).toBeTruthy();
    expect(first?.expected_lifecycle_state).toBeTruthy();
    expect(first?.lifecycle_defect_type).toBeTruthy();
    expect(typeof first?.business_lifecycle_interpretation).toBe("string");

    expect(result.problem_unit_summary?.lifecycle_enriched_units).toBeGreaterThan(0);
    expect(result.summary.lifecycle_enriched_units).toBeGreaterThan(0);
    expect(result.summary.problem_unit_lifecycle_domain_distribution).toBeTruthy();
    expect(result.summary.problem_unit_lifecycle_defect_distribution).toBeTruthy();
  });
});

