import { expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
  blockingVerificationChecks,
  bumpDeps,
  updateApp,
  verificationCommands,
} from "../src/update.ts";

test("dependency updates use each package's independently published version", () => {
  const pkg = {
    dependencies: {
      "@wrnexus/ui": "^0.8.8",
      "@wrnexus/core": "^0.8.8",
      "@wrnexus/unavailable": "^0.8.7",
    },
    devDependencies: { "@wrnexus/cli": "^0.8.8" },
  };
  const changes = bumpDeps(
    pkg,
    "0.8.9",
    new Map([
      ["@wrnexus/ui", "0.8.10"],
      ["@wrnexus/core", "0.8.8"],
      ["@wrnexus/cli", "0.8.9"],
    ]),
  );

  expect(pkg.dependencies["@wrnexus/ui"]).toBe("^0.8.10");
  expect(pkg.dependencies["@wrnexus/core"]).toBe("^0.8.8");
  expect(pkg.dependencies["@wrnexus/unavailable"]).toBe("^0.8.7");
  expect(pkg.devDependencies["@wrnexus/cli"]).toBe("^0.8.9");
  expect(changes).toHaveLength(2);
});

test("updateApp migrates project files without marking an unverified update complete", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({
      name: "legacy-app",
      scripts: { dev: "wrnexus dev ." },
      dependencies: { "@wrnexus/core": "0.2.13" },
      wrnexus: { version: "0.2.13" },
    }),
  );
  writeFileSync(join(root, ".gitignore"), "node_modules/\n");

  try {
    const result = updateApp(root, "0.2.14", false);
    expect(result).not.toBeNull();
    const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
    expect(pkg.dependencies["@wrnexus/core"]).toBe("^0.2.14");
    expect(pkg.scripts.build).toBe("wrnexus build .");
    expect(pkg.scripts.start).toBe("bun dist/server.js");
    expect(pkg.scripts.production).toBe("bun run build && bun run start");
    expect(pkg.wrnexus.version).toBe("0.2.13");

    const gitignore = readFileSync(join(root, ".gitignore"), "utf8");
    expect(gitignore).toContain("!.env.example");
    expect(gitignore).toContain("mobile/android/");
    expect(readFileSync(join(root, "public", "llms.txt"), "utf8")).toContain("# WrNexus");
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("0.2.18 migration adds helpers to existing apps and is idempotent", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({
      name: "existing-app",
      dependencies: { "@wrnexus/core": "^0.2.17" },
      wrnexus: { version: "0.2.17" },
    }),
  );

  try {
    updateApp(root, "0.2.18", false);
    updateApp(root, "0.2.18", false);
    const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
    expect(pkg.dependencies["@wrnexus/helpers"]).toBe("^0.2.18");
    expect(
      Object.keys(pkg.dependencies).filter((name) => name === "@wrnexus/helpers"),
    ).toHaveLength(1);
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("0.2.70 migration pins the production runtime directly in runnable apps", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({
      name: "existing-app",
      dependencies: { "@wrnexus/core": "^0.2.69" },
      wrnexus: { version: "0.2.69" },
    }),
  );

  try {
    updateApp(root, "0.2.70", false);
    updateApp(root, "0.2.70", false);
    const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
    expect(pkg.dependencies["@wrnexus/dev-server"]).toBe("^0.2.70");
    expect(
      Object.keys(pkg.dependencies).filter((name) => name === "@wrnexus/dev-server"),
    ).toHaveLength(1);
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("0.2.19 migration adds VS Code formatting defaults without overwriting settings", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  mkdirSync(join(root, ".vscode"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({ name: "editor-app", wrnexus: { version: "0.2.18" } }),
  );
  writeFileSync(join(root, ".gitignore"), ".vscode/\n");
  writeFileSync(join(root, ".prettierignore"), "node_modules/\n");
  writeFileSync(join(root, ".vscode", "settings.json"), '{"editor.tabSize":4}\n');

  try {
    updateApp(root, "0.2.19", false);
    updateApp(root, "0.2.19", false);

    expect(readFileSync(join(root, ".vscode", "settings.json"), "utf8")).toBe(
      '{"editor.tabSize":4}\n',
    );
    expect(readFileSync(join(root, ".vscode", "extensions.json"), "utf8")).toContain(
      "wrnexus.wrnexus",
    );
    expect(readFileSync(join(root, ".vscode", "extensions.json"), "utf8")).toBe(
      '{\n  "recommendations": ["wrnexus.wrnexus", "esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]\n}\n',
    );
    expect(readFileSync(join(root, ".prettierignore"), "utf8")).toBe("node_modules/\nCLAUDE.md\n");
    const gitignore = readFileSync(join(root, ".gitignore"), "utf8");
    expect(gitignore).not.toContain(".vscode/\n");
    expect(gitignore).toContain("!.vscode/settings.json");
    expect(gitignore).toContain("!.vscode/extensions.json");
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("0.2.20 migration repairs only the legacy generated recommendations layout", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  mkdirSync(join(root, ".vscode"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({ name: "editor-app", wrnexus: { version: "0.2.19" } }),
  );
  writeFileSync(
    join(root, ".vscode", "extensions.json"),
    JSON.stringify(
      {
        recommendations: ["wrnexus.wrnexus", "esbenp.prettier-vscode", "dbaeumer.vscode-eslint"],
      },
      null,
      2,
    ) + "\n",
  );

  try {
    updateApp(root, "0.2.20", false);
    expect(readFileSync(join(root, ".vscode", "extensions.json"), "utf8")).toBe(
      '{\n  "recommendations": ["wrnexus.wrnexus", "esbenp.prettier-vscode", "dbaeumer.vscode-eslint"]\n}\n',
    );
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("update verification formats before checking and building", () => {
  expect(
    verificationCommands({
      format: "prettier . --write",
      check: "bun run lint && bun run format:check",
      build: "wrnexus build .",
    }),
  ).toEqual([
    ["run", "format"],
    ["run", "check"],
    ["run", "build"],
  ]);
});

test("update verification skips unavailable scripts", () => {
  expect(verificationCommands({ check: "bun run lint" })).toEqual([["run", "check"]]);
});

test("0.6 type declarations are created only inside runnable apps", () => {
  const workspaceRoot = mkdtempSync(join(tmpdir(), "wrnexus-update-workspace-"));
  const appRoot = join(workspaceRoot, "apps", "web");
  mkdirSync(join(appRoot, "app", "pages"), { recursive: true });
  writeFileSync(
    join(workspaceRoot, "package.json"),
    JSON.stringify({ name: "workspace", wrnexus: { version: "0.5.9" } }),
  );
  writeFileSync(
    join(appRoot, "package.json"),
    JSON.stringify({ name: "web", wrnexus: { version: "0.5.9" } }),
  );

  try {
    updateApp(workspaceRoot, "0.6.0", false);
    updateApp(appRoot, "0.6.0", false);

    expect(existsSync(join(workspaceRoot, "app", "types", "global.d.ts"))).toBe(false);
    expect(existsSync(join(appRoot, "app", "types", "global.d.ts"))).toBe(true);
  } finally {
    rmSync(workspaceRoot, { recursive: true, force: true });
  }
});

test("0.3 WRN source normalization is conservative and idempotent", async () => {
  const { migrateWrnSource } = await import("../src/update.ts");
  const source = `component Card {
    props { eyebrow = "" title = "" description = "" align = "start" class = "" }
    view {
      <FeatureList items={items} emptyLabel="No items" />
      <button @click={save()} data-config={{ nested: true }}>Save</button>
    }
  }`;

  const migrated = migrateWrnSource(source);
  expect(migrated).toContain("props {\n");
  expect(migrated).toContain('    eyebrow = ""');
  expect(migrated).toContain("items='{items}'");
  expect(migrated).toContain("@click='{save()}'");
  // Nested brace expressions are deliberately left untouched for manual review.
  expect(migrated).toContain("data-config={{ nested: true }}");
  expect(migrateWrnSource(migrated)).toBe(migrated);
});
test("update verification allows pending marker and configuration warnings", () => {
  expect(
    blockingVerificationChecks([
      {
        name: "update marker",
        ok: false,
        detail: "project last migrated to 0.2.79",
        level: "warning",
      },
      {
        name: "configuration",
        ok: false,
        detail: "No wrnexus.config file; framework defaults will be used",
        level: "warning",
      },
    ]),
  ).toEqual([]);
});

test("update verification still blocks real doctor errors", () => {
  const fatal = {
    name: "WRN language",
    ok: false,
    detail: "10 files, 1 errors, 0 warnings",
  };

  expect(
    blockingVerificationChecks([
      fatal,
      {
        name: "update marker",
        ok: false,
        detail: "project last migrated to 0.2.79",
        level: "warning",
      },
    ]),
  ).toEqual([fatal]);
});

test("0.4 migration removes manual CAPTCHA runtime wiring and archives copied assets", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-"));
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  mkdirSync(join(root, "public", "assets", "wrnexus"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({
      name: "captcha-app",
      scripts: { dev: "wrnexus dev ." },
      dependencies: { "@wrnexus/captcha": "^0.3.6" },
      wrnexus: { version: "0.3.6" },
    }),
  );
  writeFileSync(
    join(root, "app", "pages", "index.wrn"),
    `page Home {
      view {
        <Captcha type="number" action="login" />
        <script src="/assets/wrnexus/captcha.js" defer></script>
      }
    }`,
  );
  writeFileSync(
    join(root, "public", "assets", "wrnexus", "captcha.js"),
    "window.legacyCaptcha = true;\n",
  );

  try {
    updateApp(root, "0.4.0", false);
    const page = readFileSync(join(root, "app", "pages", "index.wrn"), "utf8");
    const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
    expect(page).toContain("<Captcha");
    expect(page).not.toContain("captcha.js");
    expect(pkg.dependencies["@wrnexus/captcha"]).toBe("^0.4.0");
    expect(pkg.scripts["inspect:runtimes"]).toBe("wrnexus inspect runtimes .");
    expect(
      readFileSync(
        join(
          root,
          ".wrnexus",
          "legacy-assets",
          "0.4.0",
          "public",
          "assets",
          "wrnexus",
          "captcha.js",
        ),
        "utf8",
      ),
    ).toContain("legacyCaptcha");
    expect(existsSync(join(root, "public", "assets", "wrnexus", "captcha.js"))).toBe(false);
    const report = JSON.parse(
      readFileSync(join(root, ".wrnexus", "migrations", "0.4.0.json"), "utf8"),
    );
    expect(report.manualCaptchaRuntimeRequired).toBe(false);
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});

test("0.8 migration modernizes every WRN source with imports and a review report", () => {
  const root = mkdtempSync(join(tmpdir(), "wrnexus-update-current-source-"));
  mkdirSync(join(root, "app", "components"), { recursive: true });
  mkdirSync(join(root, "app", "layouts"), { recursive: true });
  mkdirSync(join(root, "app", "pages"), { recursive: true });
  writeFileSync(
    join(root, "package.json"),
    JSON.stringify({
      name: "source-app",
      dependencies: { "@wrnexus/core": "^0.7.0" },
      wrnexus: { version: "0.7.0" },
    }),
  );
  writeFileSync(
    join(root, "app", "components", "Notice.wrn"),
    'component Notice {\r\n  props { label = "Ready" count = 1 }   \r\n  view { <p>{label}</p> }\r\n}',
  );
  writeFileSync(
    join(root, "app", "layouts", "shell.wrn"),
    "layout Shell {\n  view { <main><slot /></main> }\n}\n",
  );
  writeFileSync(
    join(root, "app", "pages", "index.wrn"),
    'page Home {\n  layout = "shell"\n  view { <Notice label={"Updated"} /> <Missing /> }\n}\n',
  );

  try {
    updateApp(root, "0.8.0", false);
    const first = readFileSync(join(root, "app", "pages", "index.wrn"), "utf8");
    expect(first).toContain('import Notice from "@/components/Notice.wrn"');
    expect(first).toContain('import Shell from "@/layouts/shell.wrn"');
    expect(first).toContain("layout = Shell");
    expect(first).toContain("label='{\"Updated\"}'");
    expect(first.endsWith("\n")).toBe(true);

    const component = readFileSync(join(root, "app", "components", "Notice.wrn"), "utf8");
    expect(component).toContain('props {\n    label = "Ready"\n    count = 1\n  }');
    expect(component).not.toContain("\r");

    const reportPath = join(root, ".wrnexus", "migrations", "0.8.0-source-modernization.json");
    const report = JSON.parse(readFileSync(reportPath, "utf8"));
    expect(report.changedFiles).toContain("app/pages/index.wrn");
    expect(report.unresolvedImports).toContain(
      "app/pages/index.wrn: component 'Missing' could not be resolved",
    );

    updateApp(root, "0.8.0", false);
    expect(readFileSync(join(root, "app", "pages", "index.wrn"), "utf8")).toBe(first);
  } finally {
    rmSync(root, { recursive: true, force: true });
  }
});
