import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
  collectArchitectureGuardrailViolations,
  countLines,
  evaluateRule,
  rules,
} from "./check-architecture-guardrails.mjs";

describe("architecture guardrails", () => {
  it("counts lines consistently for maxLines checks", () => {
    assert.equal(countLines("a\nb\nc"), 3);
  });

  it("reports required, forbidden, and maxLines violations together", () => {
    const violations = evaluateRule(
      {
        file: "apps/web/src/example.ts",
        maxLines: 2,
        required: [{ pattern: /\bexpectedHelper\b/, message: "must call the extracted helper" }],
        forbidden: [{ pattern: /\binlineLogic\b/, message: "must not re-inline complex logic" }],
      },
      "inlineLogic();\nconst a = 1;\nconst b = 2;\n",
    );

    assert.deepEqual(violations, [
      "apps/web/src/example.ts: missing guardrail anchor: must call the extracted helper",
      "apps/web/src/example.ts: forbidden pattern matched: must not re-inline complex logic",
      "apps/web/src/example.ts: file grew to 4 lines and exceeds maxLines=2; split the ownership surface before expanding it further",
    ]);
  });

  it("returns no violations when a rule is satisfied", () => {
    const violations = evaluateRule(
      {
        file: "packages/api/src/example.ts",
        maxLines: 4,
        required: [{ pattern: /\bderiveThing\b/, message: "must keep derivation centralized" }],
        forbidden: [{ pattern: /\bunsafeThing\b/, message: "must not use unsafe helper" }],
      },
      "export function deriveThing() {\n  return true;\n}\n",
    );

    assert.deepEqual(violations, []);
  });

  it("reads sources through the injected reader when collecting violations", async () => {
    const violations = await collectArchitectureGuardrailViolations(
      [
        {
          file: "apps/web/src/example.ts",
          maxLines: 2,
          required: [],
          forbidden: [],
        },
      ],
      {
        workspaceRoot: "/virtual/repo",
        readSource: async (filePath) => {
          assert.equal(filePath, "/virtual/repo/apps/web/src/example.ts");
          return "line1\nline2\nline3\n";
        },
      },
    );

    assert.deepEqual(violations, [
      "apps/web/src/example.ts: file grew to 4 lines and exceeds maxLines=2; split the ownership surface before expanding it further",
    ]);
  });

  it("guards the extracted timeline live preview ownership boundary", () => {
    const dragRule = rules.find((rule) => rule.file === "apps/web/src/hooks/useTimelineDrag.ts");
    const livePreviewRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineLivePreview.ts");
    const touchRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineTouch.ts");
    const touchAdaptersRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineTouchAdapters.ts");
    const touchEventsRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineTouchEvents.ts");
    const multiSelectRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineMultiSelect.ts");
    const multiSelectSessionRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineMultiSelectSession.ts");
    const rangeRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineRangeSelection.ts");
    const rangeReleaseRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineRangeRelease.ts");
    const optimisticRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineOptimisticAllocations.ts");
    const previewSessionRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelinePreviewSession.ts");
    const allocationFinalizeRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineAllocationFinalize.ts");
    const allocationMultiDragRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineAllocationMultiDrag.ts");
    const allocationMultiDragSessionRule = rules.find(
      (rule) => rule.file === "apps/web/src/hooks/timelineAllocationMultiDragSession.ts",
    );
    const allocationActionsRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineAllocationActions.ts");
    const allocationReleaseRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineAllocationRelease.ts");
    const cleanupRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineDragCleanup.ts");
    const positionRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineDragPosition.ts");
    const documentDragRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineDocumentDrag.ts");
    const allocationDragStateRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineAllocationDragState.ts");
    const allocationDragSessionRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineAllocationDragSession.ts");
    const allocationReleaseEffectsRule = rules.find(
      (rule) => rule.file === "apps/web/src/hooks/timelineAllocationReleaseEffects.ts",
    );
    const projectDragRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineProjectDrag.ts");
    const projectDragFinalizeRule = rules.find(
      (rule) => rule.file === "apps/web/src/hooks/timelineProjectDragFinalize.ts",
    );
    const projectDragSessionRule = rules.find((rule) => rule.file === "apps/web/src/hooks/timelineProjectDragSession.ts");

    assert.ok(dragRule);
    assert.ok(livePreviewRule);
    assert.ok(touchRule);
    assert.ok(touchAdaptersRule);
    assert.ok(touchEventsRule);
    assert.ok(multiSelectRule);
    assert.ok(multiSelectSessionRule);
    assert.ok(rangeRule);
    assert.ok(rangeReleaseRule);
    assert.ok(optimisticRule);
    assert.ok(previewSessionRule);
    assert.ok(allocationFinalizeRule);
    assert.ok(allocationMultiDragRule);
    assert.ok(allocationMultiDragSessionRule);
    assert.ok(allocationActionsRule);
    assert.ok(allocationReleaseRule);
    assert.ok(cleanupRule);
    assert.ok(positionRule);
    assert.ok(documentDragRule);
    assert.ok(allocationDragStateRule);
    assert.ok(allocationDragSessionRule);
    assert.ok(allocationReleaseEffectsRule);
    assert.ok(projectDragRule);
    assert.ok(projectDragFinalizeRule);
    assert.ok(projectDragSessionRule);

    assert.deepEqual(evaluateRule(dragRule, "function clearLivePreview() {}\n"), [
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep live preview behavior delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep touch event forwarding delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep multi-select rectangle lifecycle delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep multi-select document session wiring delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep range preview and finalization delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep range release and cancel delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep optimistic allocation reconciliation delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep preview target setup delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep unmount teardown delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project and allocation drag position derivation delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep document mouse listener lifecycle delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation multi-drag rules delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation multi-drag document session wiring delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation drag bootstrap delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation drag document session wiring delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation release side effects delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project drag bootstrap delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project drag completion delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project drag document session wiring delegated to the extracted helper module",
      "apps/web/src/hooks/useTimelineDrag.ts: forbidden pattern matched: timeline drag must not re-inline live preview helper implementations",
    ]);

    assert.deepEqual(evaluateRule(livePreviewRule, "export function scheduleLivePreview() {}\n"), [
      "apps/web/src/hooks/timelineLivePreview.ts: missing guardrail anchor: timeline live preview helpers must keep preview reset logic centralized",
      "apps/web/src/hooks/timelineLivePreview.ts: missing guardrail anchor: timeline live preview helpers must keep snapshot preservation centralized",
    ]);

    assert.deepEqual(evaluateRule(touchRule, "export function getTouchPoint() {}\n"), [
      "apps/web/src/hooks/timelineTouch.ts: missing guardrail anchor: timeline touch helpers must keep scroll-vs-drag disambiguation centralized",
    ]);

    assert.deepEqual(evaluateRule(touchAdaptersRule, ""), [
      "apps/web/src/hooks/timelineTouchAdapters.ts: missing guardrail anchor: timeline touch adapter helpers must keep touch-to-mouse adapter wiring centralized",
      "apps/web/src/hooks/timelineTouchAdapters.ts: missing guardrail anchor: timeline touch adapter helpers must keep canvas pointer adapter wiring centralized",
    ]);

    assert.deepEqual(evaluateRule(touchEventsRule, ""), [
      "apps/web/src/hooks/timelineTouchEvents.ts: missing guardrail anchor: timeline touch event helpers must keep touch-start forwarding centralized",
      "apps/web/src/hooks/timelineTouchEvents.ts: missing guardrail anchor: timeline touch event helpers must keep touch-move forwarding centralized",
      "apps/web/src/hooks/timelineTouchEvents.ts: missing guardrail anchor: timeline touch event helpers must keep touch-end forwarding centralized",
      "apps/web/src/hooks/timelineTouchEvents.ts: missing guardrail anchor: timeline touch event helpers must keep touch policy delegated to the extracted helper module",
      "apps/web/src/hooks/timelineTouchEvents.ts: missing guardrail anchor: timeline touch event helpers must keep touch adapter wiring delegated to the extracted helper module",
    ]);

    assert.deepEqual(evaluateRule(multiSelectRule, "export function createMultiSelectState() {}\n"), [
      "apps/web/src/hooks/timelineMultiSelect.ts: missing guardrail anchor: timeline multi-select helpers must keep minimal-drag reset logic centralized",
      "apps/web/src/hooks/timelineMultiSelect.ts: missing guardrail anchor: timeline multi-select helpers must keep right-click release completion centralized",
    ]);

    assert.deepEqual(evaluateRule(multiSelectSessionRule, ""), [
      "apps/web/src/hooks/timelineMultiSelectSession.ts: missing guardrail anchor: timeline multi-select session helpers must keep right-click session lifecycle centralized",
    ]);

    assert.deepEqual(evaluateRule(rangeRule, "export function updateRangeSelectionDraft() {}\n"), [
      "apps/web/src/hooks/timelineRangeSelection.ts: missing guardrail anchor: timeline range helpers must keep selection bootstrap centralized",
      "apps/web/src/hooks/timelineRangeSelection.ts: missing guardrail anchor: timeline range helpers must keep ordered range finalization centralized",
    ]);

    assert.deepEqual(evaluateRule(rangeReleaseRule, "export function resolveRangeSelectionRelease() {}\n"), [
      "apps/web/src/hooks/timelineRangeRelease.ts: missing guardrail anchor: timeline range release helpers must keep canvas leave cancellation centralized",
      "apps/web/src/hooks/timelineRangeRelease.ts: missing guardrail anchor: timeline range release helpers must keep selection finalization delegated to the range helper module",
    ]);

    assert.deepEqual(evaluateRule(optimisticRule, ""), [
      "apps/web/src/hooks/timelineOptimisticAllocations.ts: missing guardrail anchor: timeline optimistic helpers must keep server-reconciliation logic centralized",
    ]);

    assert.deepEqual(evaluateRule(previewSessionRule, "export function createProjectPreviewSession() {}\n"), [
      "apps/web/src/hooks/timelinePreviewSession.ts: missing guardrail anchor: timeline preview session helpers must keep allocation preview target resolution centralized",
      "apps/web/src/hooks/timelinePreviewSession.ts: missing guardrail anchor: timeline preview session helpers must keep target capture delegated to the live preview helper module",
    ]);

    assert.deepEqual(evaluateRule(allocationFinalizeRule, "export function hasAllocationDateChange() {}\n"), [
      "apps/web/src/hooks/timelineAllocationFinalize.ts: missing guardrail anchor: timeline allocation finalize helpers must keep click-vs-drag classification centralized",
      "apps/web/src/hooks/timelineAllocationFinalize.ts: missing guardrail anchor: timeline allocation finalize helpers must keep segment extraction rules centralized",
      "apps/web/src/hooks/timelineAllocationFinalize.ts: missing guardrail anchor: timeline allocation finalize helpers must keep mutation snapshot creation centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationMultiDragRule, "export function isAllocationMultiSelected() {}\n"), [
      "apps/web/src/hooks/timelineAllocationMultiDrag.ts: missing guardrail anchor: timeline allocation multi-drag helpers must keep same-day delta suppression centralized",
      "apps/web/src/hooks/timelineAllocationMultiDrag.ts: missing guardrail anchor: timeline allocation multi-drag helpers must keep reset-on-release behavior centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationMultiDragSessionRule, ""), [
      "apps/web/src/hooks/timelineAllocationMultiDragSession.ts: missing guardrail anchor: timeline allocation multi-drag session helpers must keep document drag lifecycle centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationActionsRule, "export function buildAllocationBlockClickInfo() {}\n"), [
      "apps/web/src/hooks/timelineAllocationActions.ts: missing guardrail anchor: timeline allocation action helpers must keep mutation plan derivation centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationReleaseRule, ""), [
      "apps/web/src/hooks/timelineAllocationRelease.ts: missing guardrail anchor: timeline allocation release helpers must keep release classification centralized",
      "apps/web/src/hooks/timelineAllocationRelease.ts: missing guardrail anchor: timeline allocation release helpers must keep click and mutation plan derivation delegated to allocation action helpers",
    ]);

    assert.deepEqual(evaluateRule(cleanupRule, ""), [
      "apps/web/src/hooks/timelineDragCleanup.ts: missing guardrail anchor: timeline drag cleanup helpers must keep unmount teardown centralized",
    ]);

    assert.deepEqual(evaluateRule(positionRule, "export function resolveProjectDragPosition() {}\n"), [
      "apps/web/src/hooks/timelineDragPosition.ts: missing guardrail anchor: timeline drag position helpers must keep allocation drag date derivation centralized",
    ]);

    assert.deepEqual(evaluateRule(documentDragRule, ""), [
      "apps/web/src/hooks/timelineDocumentDrag.ts: missing guardrail anchor: timeline document drag helpers must keep document mouse listener wiring centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationDragStateRule, ""), [
      "apps/web/src/hooks/timelineAllocationDragState.ts: missing guardrail anchor: timeline allocation drag state helpers must keep drag bootstrap centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationDragSessionRule, ""), [
      "apps/web/src/hooks/timelineAllocationDragSession.ts: missing guardrail anchor: timeline allocation drag session helpers must keep document drag lifecycle centralized",
    ]);

    assert.deepEqual(evaluateRule(allocationReleaseEffectsRule, ""), [
      "apps/web/src/hooks/timelineAllocationReleaseEffects.ts: missing guardrail anchor: timeline allocation release effect helpers must keep release side effects centralized",
      "apps/web/src/hooks/timelineAllocationReleaseEffects.ts: missing guardrail anchor: timeline allocation release effect helpers must keep release classification delegated to the extracted helper module",
      "apps/web/src/hooks/timelineAllocationReleaseEffects.ts: missing guardrail anchor: timeline allocation release effect helpers must keep preview lifecycle delegated to the extracted helper module",
    ]);

    assert.deepEqual(evaluateRule(projectDragRule, "export function createProjectDragState() {}\n"), [
      "apps/web/src/hooks/timelineProjectDrag.ts: missing guardrail anchor: timeline project drag helpers must keep no-op project-shift mutation gating centralized",
    ]);

    assert.deepEqual(evaluateRule(projectDragFinalizeRule, ""), [
      "apps/web/src/hooks/timelineProjectDragFinalize.ts: missing guardrail anchor: timeline project drag finalize helpers must keep completion flow centralized",
      "apps/web/src/hooks/timelineProjectDragFinalize.ts: missing guardrail anchor: timeline project drag finalize helpers must keep mutation gating delegated to the project drag helper module",
      "apps/web/src/hooks/timelineProjectDragFinalize.ts: missing guardrail anchor: timeline project drag finalize helpers must keep preview preservation delegated to the live preview helper module",
    ]);

    assert.deepEqual(evaluateRule(projectDragSessionRule, ""), [
      "apps/web/src/hooks/timelineProjectDragSession.ts: missing guardrail anchor: timeline project drag session helpers must keep document drag lifecycle centralized",
    ]);

    assert.deepEqual(
      evaluateRule(
        dragRule,
        'import { getTouchPoint } from "./timelineTouch.js";\n',
      ),
      [
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep live preview behavior delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep touch event forwarding delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep multi-select rectangle lifecycle delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep multi-select document session wiring delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep range preview and finalization delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep range release and cancel delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep optimistic allocation reconciliation delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep preview target setup delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep unmount teardown delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project and allocation drag position derivation delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep document mouse listener lifecycle delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation multi-drag rules delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation multi-drag document session wiring delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation drag bootstrap delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation drag document session wiring delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep allocation release side effects delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project drag bootstrap delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project drag completion delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: missing guardrail anchor: timeline drag must keep project drag document session wiring delegated to the extracted helper module",
        "apps/web/src/hooks/useTimelineDrag.ts: forbidden pattern matched: timeline drag must not re-inline extracted touch event forwarding dependencies",
      ],
    );
  });
});
