import { existsSync, readdirSync, statSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CHATBOT_DIR = path.resolve(__dirname, "..");
const REPO_ROOT = path.resolve(CHATBOT_DIR, "..");
const AUTOMATION_DIR = path.join(REPO_ROOT, "automation");

export const DEFAULT_CHATBOT_PROFILE_DIR = path.join(CHATBOT_DIR, ".browser", "1688-profile");
export const AUTOMATION_LEGACY_PROFILE_DIR = path.join(AUTOMATION_DIR, ".browser", "1688-profile");
export const AUTOMATION_ACCOUNT_PROFILE_ROOT = path.join(AUTOMATION_DIR, ".browser", "1688-profiles");

function resolvePathMaybeRelative(value, cwd) {
  return path.isAbsolute(value) ? value : path.resolve(cwd, value);
}

function hasUsableProfile(dir) {
  if (!dir || !existsSync(dir)) {
    return false;
  }

  try {
    return statSync(dir).isDirectory();
  } catch {
    return false;
  }
}

function sanitizeProfileSegment(value) {
  return String(value ?? "").trim().replace(/[^a-zA-Z0-9_-]/g, "_");
}

function getAccountProfileDir(accountId, accountProfileRoot) {
  const normalized = sanitizeProfileSegment(accountId);
  if (!normalized) {
    return "";
  }

  return path.join(accountProfileRoot, normalized);
}

function getSingleAccountProfileDir(accountProfileRoot) {
  if (!hasUsableProfile(accountProfileRoot)) {
    return "";
  }

  try {
    const candidates = readdirSync(accountProfileRoot)
      .map((name) => path.join(accountProfileRoot, name))
      .filter(hasUsableProfile);
    return candidates.length === 1 ? candidates[0] : "";
  } catch {
    return "";
  }
}

export function resolveChatProfileDir({
  env = process.env,
  cwd = process.cwd(),
  defaultProfileDir = DEFAULT_CHATBOT_PROFILE_DIR,
  legacyAutomationProfileDir = AUTOMATION_LEGACY_PROFILE_DIR,
  accountProfileRoot = AUTOMATION_ACCOUNT_PROFILE_ROOT,
} = {}) {
  const explicitProfileDir = env.CHAT_1688_PROFILE_DIR || env.SEARCH_1688_PROFILE_DIR || "";
  if (explicitProfileDir) {
    return resolvePathMaybeRelative(explicitProfileDir, cwd);
  }

  const accountId = env.CHAT_1688_ACCOUNT_ID || env.SEARCH_1688_ACCOUNT_ID || "";
  const accountProfileDir = getAccountProfileDir(accountId, accountProfileRoot);
  if (hasUsableProfile(accountProfileDir)) {
    return accountProfileDir;
  }

  const singleAccountProfileDir = getSingleAccountProfileDir(accountProfileRoot);
  if (singleAccountProfileDir) {
    return singleAccountProfileDir;
  }

  if (hasUsableProfile(legacyAutomationProfileDir)) {
    return legacyAutomationProfileDir;
  }

  return defaultProfileDir;
}
