import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import postgres from "postgres";
import { approvedJourneyEnvironment, requiredEnvironment } from "./exact-journey.js";
import { canonicalGitHubRepository } from "./repository-identity.js";

const databaseUrl = requiredEnvironment(process.env, "AWP_TEST_POSTGRES_URL");
const repository = requiredEnvironment(process.env, "AWP_REPOSITORY_CHECKOUT_PATH");
const repositoryUrl = requiredEnvironment(process.env, "AWP_REPOSITORY_REMOTE_URL");
const defaultBranch = requiredEnvironment(process.env, "AWP_REPOSITORY_DEFAULT_BRANCH");
const { factoryRunId, projectId, taskIds } = approvedJourneyEnvironment();

const origin = execFileSync("git", ["remote", "get-url", "origin"], {
  cwd: repository,
  encoding: "utf8",
}).trim();
assert.equal(canonicalGitHubRepository(origin), canonicalGitHubRepository(repositoryUrl));

const sql = postgres(databaseUrl, { max: 1 });
try {
  const changes = await sql<{ change_set_id: string; task_id: string }[]>`
    select cs.id as change_set_id, cs.task_id
    from change_sets cs
    join attempts a on a.id = cs.producer_attempt_id
    join agent_runs ar on ar.id = a.agent_run_id
    join tasks t on t.id = cs.task_id and t.project_id = cs.project_id
    where cs.project_id = ${projectId}
      and ar.factory_run_id = ${factoryRunId}
      and cs.status = 'merged'
    order by t.position, cs.id
  `;
  assert.deepEqual(
    changes.map((change) => change.task_id),
    [...taskIds],
    "the exact self FactoryRun must retain one merged ChangeSet for each canonical Task",
  );

  execFileSync("git", ["fetch", "origin", defaultBranch], { cwd: repository, stdio: "pipe" });
  const commits: string[] = [];
  for (const change of changes) {
    const commitOutput = execFileSync(
      "git",
      [
        "log",
        `origin/${defaultBranch}`,
        "-1",
        "--fixed-strings",
        `--grep=AWP-ChangeSet: ${change.change_set_id}`,
        "--format=%H%n%B",
      ],
      { cwd: repository, encoding: "utf8" },
    ).trim();
    const [commitSha, ...bodyLines] = commitOutput.split("\n");
    assert.ok(
      commitSha,
      `self ChangeSet ${change.change_set_id} must exist on origin/${defaultBranch}`,
    );
    const body = bodyLines.join("\n");
    assert.match(body, new RegExp(`^AWP-FactoryRun: ${factoryRunId}$`, "m"));
    assert.match(body, new RegExp(`^AWP-ChangeSet: ${change.change_set_id}$`, "m"));
    commits.push(commitSha);
  }
  process.stdout.write(
    `AC-29 PASS: exact AWP FactoryRun ${factoryRunId} authored and trusted-merged canonical ChangeSets ${changes.map((change) => change.change_set_id).join(",")} into origin/${defaultBranch} at commits ${commits.join(",")}\n`,
  );
} finally {
  await sql.end({ timeout: 5 });
}
