import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { test } from "bun:test";

import { runHwpodCli } from "../src/hwpod-harness-lib.ts";

test("hwpod-cli help exposes workspace cat and apply-patch stdin usage", async () => {
  const result = await runHwpodCli(["help"], { now: () => "2026-06-06T00:00:00.000Z" });

  assert.equal(result.exitCode, 0);
  assert.equal(result.payload.action, "hwpod-cli.help");
  assert.equal(result.payload.usage.some((item: string) => /workspace cat/u.test(item)), true);
  assert.equal(result.payload.usage.some((item: string) => /workspace apply-patch/u.test(item)), true);
  assert.match(result.payload.applyPatchExample, /\*\*\* Begin Patch/u);
});

test("hwpod-cli workspace apply-patch passes stdin patch to hwpod-node plan", async () => {
  const root = await mkdtemp(path.join(os.tmpdir(), "hwpod-cli-test-"));
  const specPath = path.join(root, "hwpod-spec.yaml");
  const patch = "*** Begin Patch\n*** Update File: app.c\n@@\n old\n+new\n*** End Patch\n";
  try {
    await writeFile(specPath, hwpodSpecText(), "utf8");
    const result = await runHwpodCli(["workspace", "apply-patch", "--spec", specPath, "--reason", "test", "--dry-run"], {
      stdinText: patch,
      now: () => "2026-06-06T00:00:00.000Z"
    });

    assert.equal(result.exitCode, 0);
    assert.equal(result.payload.action, "hwpod-cli.plan");
    assert.equal(result.payload.intent, "workspace.apply-patch");
    assert.equal(result.payload.plan.ops[0].op, "workspace.apply-patch");
    assert.equal(result.payload.plan.ops[0].args.patch, patch);
    assert.equal(result.payload.plan.ops[0].args.reason, "test");
  } finally {
    await rm(root, { recursive: true, force: true });
  }
});

test("hwpod-cli workspace apply-patch accepts --patch-content alias", async () => {
  const root = await mkdtemp(path.join(os.tmpdir(), "hwpod-cli-test-patch-content-"));
  const specPath = path.join(root, "hwpod-spec.yaml");
  const patch = "*** Begin Patch\n*** Update File: app.c\n@@\n-old\n+new\n*** End Patch\n";
  try {
    await writeFile(specPath, hwpodSpecText(), "utf8");
    const result = await runHwpodCli(["workspace", "apply-patch", "--spec", specPath, "--patch-content", patch, "--dry-run"], {
      now: () => "2026-06-06T00:00:00.000Z"
    });

    assert.equal(result.exitCode, 0);
    assert.equal(result.payload.intent, "workspace.apply-patch");
    assert.equal(result.payload.plan.ops[0].args.patch, patch);
  } finally {
    await rm(root, { recursive: true, force: true });
  }
});

function hwpodSpecText() {
  return "kind: Hwpod\nmetadata:\n  name: test-hwpod\nspec:\n  nodeBinding:\n    nodeId: test-node\n  workspace:\n    path: F:\\\\Work\\\\HWLAB-CASE-F103\n  targetDevice:\n    board: D601-F103-V2\n  debugProbe:\n    type: daplink\n  ioProbe:\n    uart:\n      port: COM9\n";
}
