import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { execSync } from "node:child_process";
import { readGitState } from "@/lib/git/scanner";

let repoDir: string;

beforeAll(() => {
  repoDir = mkdtempSync(join(tmpdir(), "pm-git-"));
  execSync("git init -b main", { cwd: repoDir });
  execSync("git config user.email t@t.io", { cwd: repoDir });
  execSync("git config user.name tester", { cwd: repoDir });
  writeFileSync(join(repoDir, "package.json"), JSON.stringify({ name: "demo", version: "1.2.3" }));
  execSync("git add . && git commit -m 'init commit'", { cwd: repoDir });
  execSync("git remote add origin https://example.com/demo.git", { cwd: repoDir });
});

afterAll(() => {
  rmSync(repoDir, { recursive: true, force: true });
});

describe("readGitState", () => {
  it("reads branch, remote, last commit, version from package.json", async () => {
    const state = await readGitState(repoDir);
    expect(state.branch).toBe("main");
    expect(state.gitRemote).toBe("https://example.com/demo.git");
    expect(state.lastCommitHash).toMatch(/^[0-9a-f]{40}$/);
    expect(state.lastCommitMessage).toContain("init commit");
    expect(state.version).toBe("1.2.3");
    expect(state.lastCommitTime).toBeInstanceOf(Date);
  });

  it("returns null fields for non-git directory", async () => {
    const empty = mkdtempSync(join(tmpdir(), "pm-empty-"));
    const state = await readGitState(empty);
    expect(state.branch).toBeNull();
    expect(state.lastCommitHash).toBeNull();
    rmSync(empty, { recursive: true, force: true });
  });

  it("reads version from pyproject.toml when no package.json", async () => {
    const py = mkdtempSync(join(tmpdir(), "pm-py-"));
    execSync("git init -b main", { cwd: py });
    execSync("git config user.email t@t.io", { cwd: py });
    execSync("git config user.name tester", { cwd: py });
    writeFileSync(join(py, "pyproject.toml"), '[project]\nname = "x"\nversion = "9.9.9"\n');
    execSync("git add . && git commit -m init", { cwd: py });
    const state = await readGitState(py);
    expect(state.version).toBe("9.9.9");
    rmSync(py, { recursive: true, force: true });
  });
});
