import fs from "node:fs";
import path from "node:path";
import { loadJsonFile, saveJsonFile } from "openclaw/plugin-sdk/json-store";
import {
  DEFAULT_OPENCLAW_BROWSER_COLOR,
  DEFAULT_OPENCLAW_BROWSER_PROFILE_NAME,
} from "./constants.js";

function decoratedMarkerPath(userDataDir: string) {
  return path.join(userDataDir, ".openclaw-profile-decorated");
}

function safeReadJson(filePath: string): Record<string, unknown> | null {
  const parsed = loadJsonFile(filePath);
  return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
    ? (parsed as Record<string, unknown>)
    : null;
}

function safeWriteJson(filePath: string, data: Record<string, unknown>) {
  saveJsonFile(filePath, data);
}

function asRecord(value: unknown): Record<string, unknown> | null {
  return typeof value === "object" && value !== null && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : null;
}

function readNestedRecord(root: unknown, key: string): Record<string, unknown> | null {
  return asRecord(asRecord(root)?.[key]);
}

function setDeep(obj: Record<string, unknown>, keys: string[], value: unknown) {
  let node: Record<string, unknown> = obj;
  for (const key of keys.slice(0, -1)) {
    const next = node[key];
    if (typeof next !== "object" || next === null || Array.isArray(next)) {
      node[key] = {};
    }
    node = node[key] as Record<string, unknown>;
  }
  node[keys[keys.length - 1] ?? ""] = value;
}

function parseHexRgbToSignedArgbInt(hex: string): number | null {
  const cleaned = hex.trim().replace(/^#/, "");
  if (!/^[0-9a-fA-F]{6}$/.test(cleaned)) {
    return null;
  }
  const rgb = Number.parseInt(cleaned, 16);
  const argbUnsigned = (0xff << 24) | rgb;
  // Chrome stores colors as signed 32-bit ints (SkColor).
  return argbUnsigned > 0x7fffffff ? argbUnsigned - 0x1_0000_0000 : argbUnsigned;
}

export function isProfileDecorated(
  userDataDir: string,
  desiredName: string,
  desiredColorHex: string,
  desiredDownloadDir?: string,
): boolean {
  const desiredColorInt = parseHexRgbToSignedArgbInt(desiredColorHex);

  const localStatePath = path.join(userDataDir, "Local State");
  const preferencesPath = path.join(userDataDir, "Default", "Preferences");

  const localState = safeReadJson(localStatePath);
  const profile = localState?.profile;
  const info = readNestedRecord(readNestedRecord(profile, "info_cache"), "Default");

  const prefs = safeReadJson(preferencesPath);
  const browserTheme = readNestedRecord(prefs?.browser, "theme");
  const autogeneratedTheme = readNestedRecord(prefs?.autogenerated, "theme");
  const download = readNestedRecord(prefs, "download");
  const savefile = readNestedRecord(prefs, "savefile");

  const nameOk = typeof info?.name === "string" ? info.name === desiredName : true;
  const downloadOk = desiredDownloadDir
    ? download?.default_directory === desiredDownloadDir &&
      download.prompt_for_download === false &&
      download.directory_upgrade === true &&
      savefile?.default_directory === desiredDownloadDir
    : true;

  if (desiredColorInt == null) {
    // If the user provided a non-#RRGGBB value, we can only do best-effort.
    return nameOk && downloadOk;
  }

  const localSeedOk =
    typeof info?.profile_color_seed === "number"
      ? info.profile_color_seed === desiredColorInt
      : false;

  const prefOk =
    (typeof browserTheme?.user_color2 === "number" &&
      browserTheme.user_color2 === desiredColorInt) ||
    (typeof autogeneratedTheme?.color === "number" && autogeneratedTheme.color === desiredColorInt);

  return nameOk && localSeedOk && prefOk && downloadOk;
}

/**
 * Best-effort profile decoration (name + lobster-orange). Chrome preference keys
 * vary by version; we keep this conservative and idempotent.
 */
export function decorateOpenClawProfile(
  userDataDir: string,
  opts?: { name?: string; color?: string; downloadDir?: string },
) {
  const desiredName = opts?.name ?? DEFAULT_OPENCLAW_BROWSER_PROFILE_NAME;
  const desiredColor = (opts?.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase();
  const desiredColorInt = parseHexRgbToSignedArgbInt(desiredColor);

  const localStatePath = path.join(userDataDir, "Local State");
  const preferencesPath = path.join(userDataDir, "Default", "Preferences");

  const localState = safeReadJson(localStatePath) ?? {};
  // Common-ish shape: profile.info_cache.Default
  setDeep(localState, ["profile", "info_cache", "Default", "name"], desiredName);
  setDeep(localState, ["profile", "info_cache", "Default", "shortcut_name"], desiredName);
  setDeep(localState, ["profile", "info_cache", "Default", "user_name"], desiredName);
  // Color keys are best-effort (Chrome changes these frequently).
  setDeep(localState, ["profile", "info_cache", "Default", "profile_color"], desiredColor);
  setDeep(localState, ["profile", "info_cache", "Default", "user_color"], desiredColor);
  if (desiredColorInt != null) {
    // These are the fields Chrome actually uses for profile/avatar tinting.
    setDeep(
      localState,
      ["profile", "info_cache", "Default", "profile_color_seed"],
      desiredColorInt,
    );
    setDeep(
      localState,
      ["profile", "info_cache", "Default", "profile_highlight_color"],
      desiredColorInt,
    );
    setDeep(
      localState,
      ["profile", "info_cache", "Default", "default_avatar_fill_color"],
      desiredColorInt,
    );
    setDeep(
      localState,
      ["profile", "info_cache", "Default", "default_avatar_stroke_color"],
      desiredColorInt,
    );
  }
  safeWriteJson(localStatePath, localState);

  const prefs = safeReadJson(preferencesPath) ?? {};
  setDeep(prefs, ["profile", "name"], desiredName);
  setDeep(prefs, ["profile", "profile_color"], desiredColor);
  setDeep(prefs, ["profile", "user_color"], desiredColor);
  if (desiredColorInt != null) {
    // Chrome refresh stores the autogenerated theme in these prefs (SkColor ints).
    setDeep(prefs, ["autogenerated", "theme", "color"], desiredColorInt);
    // User-selected browser theme color (pref name: browser.theme.user_color2).
    setDeep(prefs, ["browser", "theme", "user_color2"], desiredColorInt);
  }
  if (opts?.downloadDir) {
    setDeep(prefs, ["download", "default_directory"], opts.downloadDir);
    setDeep(prefs, ["download", "prompt_for_download"], false);
    setDeep(prefs, ["download", "directory_upgrade"], true);
    setDeep(prefs, ["savefile", "default_directory"], opts.downloadDir);
  }
  safeWriteJson(preferencesPath, prefs);

  try {
    fs.writeFileSync(decoratedMarkerPath(userDataDir), `${Date.now()}\n`, "utf-8");
  } catch {
    // ignore
  }
}

export function ensureProfileCleanExit(userDataDir: string) {
  const preferencesPath = path.join(userDataDir, "Default", "Preferences");
  const prefs = safeReadJson(preferencesPath) ?? {};
  setDeep(prefs, ["exit_type"], "Normal");
  setDeep(prefs, ["exited_cleanly"], true);
  safeWriteJson(preferencesPath, prefs);
}
