import path from "node:path";
import os from "node:os";
import { fileURLToPath } from "node:url";

const SCRIPT_FILE = fileURLToPath(import.meta.url);
const SCRIPT_DIR = path.dirname(SCRIPT_FILE);
const PROJECT_ROOT = path.resolve(SCRIPT_DIR, "../..");
const AUTOMATION_DIR = path.join(PROJECT_ROOT, "automation");
const DEFAULT_ACCOUNT_SEGMENT = "__default_1688_account__";

function resolvePathMaybeTilde(value, { cwd = PROJECT_ROOT, homeDir = os.homedir() } = {}) {
  const normalized = String(value ?? "").trim();
  if (!normalized) {
    return "";
  }
  if (normalized === "~") {
    return homeDir;
  }
  if (normalized.startsWith("~/")) {
    return path.join(homeDir, normalized.slice(2));
  }
  return path.isAbsolute(normalized) ? normalized : path.resolve(cwd, normalized);
}

function toAbsoluteProfileDir(value, projectRoot = PROJECT_ROOT) {
  return resolvePathMaybeTilde(value, { cwd: projectRoot });
}

export function sanitize1688ProfileSegment(value) {
  const sanitized = String(value ?? "")
    .trim()
    .replace(/[^a-zA-Z0-9_-]/g, "_")
    .replace(/_+/g, "_")
    .replace(/^_+|_+$/g, "")
    .slice(0, 80);
  return sanitized || DEFAULT_ACCOUNT_SEGMENT;
}

export function resolve1688AccountProfileRoot(options = {}) {
  const env = options.env ?? process.env;
  return resolvePathMaybeTilde(
    options.profileRoot ?? env.ALPHAPULSE_1688_PROFILE_ROOT ?? "~/.1688-autoprocurement/1688-profiles",
    {
      cwd: options.cwd ?? options.projectRoot ?? PROJECT_ROOT,
      homeDir: options.homeDir ?? os.homedir(),
    },
  );
}

export function resolve1688AccountProfileDir(options = {}) {
  const env = options.env ?? process.env;
  const cwd = options.cwd ?? options.projectRoot ?? PROJECT_ROOT;
  const homeDir = options.homeDir ?? os.homedir();
  const explicitProfileDir = resolvePathMaybeTilde(options.explicitProfileDir, { cwd, homeDir });
  if (explicitProfileDir) {
    return explicitProfileDir;
  }

  const envProfileDir = resolvePathMaybeTilde(
    options.envProfileDir ?? env.CHAT_1688_PROFILE_DIR ?? env.SEARCH_1688_PROFILE_DIR,
    { cwd, homeDir },
  );
  if (envProfileDir) {
    return envProfileDir;
  }

  const accountSegment = sanitize1688ProfileSegment(
    options.accountId ?? env.CHAT_1688_ACCOUNT_ID ?? env.SEARCH_1688_ACCOUNT_ID
      ?? options.accountName ?? env.SEARCH_1688_ACCOUNT_NAME ?? env.LOGIN_1688_USER,
  );
  return path.join(resolve1688AccountProfileRoot({ ...options, env, cwd, homeDir }), accountSegment);
}

export function inferSearchTaskProfileDirFromArtifactPath(artifactPath) {
  const normalized = String(artifactPath ?? "").trim();
  if (!normalized) {
    return "";
  }

  const absolutePath = path.resolve(normalized);
  const parts = absolutePath.split(path.sep);
  const runtimeIndex = parts.lastIndexOf(".runtime");
  if (runtimeIndex < 0 || parts[runtimeIndex + 1] !== "search-tasks" || !parts[runtimeIndex + 2]) {
    return "";
  }

  return path.join(path.sep, ...parts.slice(1, runtimeIndex + 3), "profile");
}

export function resolve1688ProfileDir(options = {}) {
  const projectRoot = options.projectRoot || PROJECT_ROOT;
  const automationDir = options.automationDir || AUTOMATION_DIR;
  const explicitProfileDir = toAbsoluteProfileDir(options.explicitProfileDir, projectRoot);
  if (explicitProfileDir) {
    return explicitProfileDir;
  }

  const envProfileDir = toAbsoluteProfileDir(
    options.envProfileDir ?? process.env.SEARCH_1688_PROFILE_DIR,
    projectRoot,
  );
  if (envProfileDir) {
    return envProfileDir;
  }

  if (options.accountId || options.accountName || process.env.SEARCH_1688_ACCOUNT_ID || process.env.LOGIN_1688_USER) {
    return resolve1688AccountProfileDir({
      ...options,
      env: options.env ?? process.env,
      cwd: projectRoot,
    });
  }

  const taskId = String(options.taskId ?? "").trim();
  if (taskId) {
    return path.join(automationDir, ".runtime", "search-tasks", taskId, "profile");
  }

  const inferredProfileDir = inferSearchTaskProfileDirFromArtifactPath(options.artifactPath);
  if (inferredProfileDir) {
    return inferredProfileDir;
  }

  if (options.allowLegacyFallback === false) {
    return "";
  }

  return resolve1688AccountProfileDir({
    ...options,
    env: options.env ?? process.env,
    cwd: projectRoot,
  });
}
