import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";

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

const REPO_ROOT = path.resolve(import.meta.dirname, "..", "..");

function trackedFiles(): string[] {
  return execFileSync("git", ["ls-files"], {
    cwd: REPO_ROOT,
    encoding: "utf8",
  })
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean);
}

function readTrackedFile(relativePath: string): string {
  return readFileSync(path.join(REPO_ROOT, relativePath), "utf8");
}

describe("legacy document runtime cleanup", () => {
  it("removes the Python conversion runtime and references from tracked files", () => {
    const forbiddenTerms = [
      "mark" + "itdown",
      "Mark" + "ItDown",
      "convert_with" + "_ocr",
    ];
    const offenders = trackedFiles().flatMap((relativePath) => {
      if (!existsSync(path.join(REPO_ROOT, relativePath))) {
        return [];
      }
      const pathHits = forbiddenTerms
        .filter((term) => relativePath.includes(term))
        .map((term) => `${relativePath} path contains ${term}`);
      let contentHits: string[] = [];
      if (!relativePath.endsWith(".mp3")) {
        const content = readTrackedFile(relativePath);
        contentHits = forbiddenTerms
          .filter((term) => content.includes(term))
          .map((term) => `${relativePath} content contains ${term}`);
      }
      return [...pathHits, ...contentHits];
    });

    expect(offenders).toEqual([]);
  });

  it("keeps deployment free of Python document conversion setup", () => {
    const deployScript = readTrackedFile("scripts/deploy.sh");

    expect(deployScript).not.toContain("uv sync");
    expect(deployScript).not.toContain("UV_BIN");
    expect(deployScript).not.toContain("install_python_dependencies");
  });

  it("removes the obsolete image text prompt seed", () => {
    const obsoletePromptKey = [
      "automation",
      "document_ocr",
      "image_text_extraction",
      "user",
    ].join(".");
    const promptSeedFiles = [
      "scripts/seed-prompt-store.ts",
      "supabase/sql/prompt-store-schema.sql",
    ];

    const offenders = promptSeedFiles.filter((relativePath) =>
      readTrackedFile(relativePath).includes(obsoletePromptKey),
    );

    expect(offenders).toEqual([]);
  });
});
