import { existsSync } from "node:fs";
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";

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

import {
  parseRecoverFixedSearchContactsArgs,
  resolveRecoverFixedSearchProfileDir,
} from "./recover-fixed-search-contacts.ts";

const tempDirs: string[] = [];

async function makeTempRoot() {
  const dir = await mkdtemp(path.join(os.tmpdir(), "recover-fixed-search-profile-"));
  tempDirs.push(dir);
  return dir;
}

afterEach(async () => {
  await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});

describe("recover fixed search contacts profile resolution", () => {
  it("infers the task runtime profile from the llm json path", async () => {
    const root = await makeTempRoot();
    const taskRoot = path.join(root, "automation", ".runtime", "search-tasks", "CG-20260429-001-ss-011");
    const profileDir = path.join(taskRoot, "profile");
    const llmJson = path.join(taskRoot, "output", "search-plan", "run-1", "llm-match-results.json");
    await mkdir(profileDir, { recursive: true });
    await mkdir(path.dirname(llmJson), { recursive: true });

    const options = parseRecoverFixedSearchContactsArgs([
      `--llm-json=${llmJson}`,
      "--no-sync-db",
    ]);

    await expect(resolveRecoverFixedSearchProfileDir(options)).resolves.toBe(profileDir);
  });

  it("fails instead of falling back to the legacy profile when no task profile is available", async () => {
    const root = await makeTempRoot();
    const llmJson = path.join(root, "detached", "llm-match-results.json");
    await mkdir(path.dirname(llmJson), { recursive: true });

    const options = parseRecoverFixedSearchContactsArgs([
      `--llm-json=${llmJson}`,
      "--no-sync-db",
    ]);

    await expect(resolveRecoverFixedSearchProfileDir(options))
      .rejects.toThrow("缺少 1688 登录态 profile，无法从 LLM JSON 恢复联系方式阶段");
    expect(existsSync(path.join(root, "automation", ".browser", "1688-profile"))).toBe(false);
  });
});
