import { spawnSync } from "node:child_process";
import { readFile } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
  isPrivateReelPreviewOrigin,
  isPrivateReelProductionOrigin,
  PRIVATE_REEL_PRODUCTION_ORIGIN,
} from "./gallery-origins.mjs";
import { tailscaleSelfURL } from "./peer-discovery.mjs";
import { resolveAgentRuntimePaths } from "./runtime-paths.mjs";

const agentDirectory = dirname(fileURLToPath(import.meta.url));
const { configPath, tailscaleCLI } = resolveAgentRuntimePaths({ agentDirectory });
const defaultGalleryURL = PRIVATE_REEL_PRODUCTION_ORIGIN;

export function requestedGalleryURL(argument, allowedOrigins = []) {
  let requested = String(argument || "").trim();
  if (requested.startsWith("privatereel:")) {
    requested = new URL(requested).searchParams.get("gallery") || "";
  }

  const value = requested || defaultGalleryURL;
  const url = new URL(value);
  const originAllowed = allowedOrigins.includes(url.origin);
  const knownGallery =
    url.protocol === "https:" &&
    (isPrivateReelProductionOrigin(url.origin) || isPrivateReelPreviewOrigin(url.origin));
  const localDevelopment =
    url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1");

  if (!originAllowed && !knownGallery && !localDevelopment) {
    throw new Error(`Private Reel will not open an unapproved gallery origin: ${url.origin}`);
  }
  url.search = "";
  url.hash = "";
  return url;
}

export function galleryBootstrapURL(galleryURL, source) {
  const target = new URL(galleryURL);
  target.hash = new URLSearchParams({ source }).toString();
  return target.toString();
}

export function localAgentURL(config = {}, env = process.env) {
  return `http://127.0.0.1:${Number(env.PRIVATE_REEL_PORT || config.port || 47821)}`;
}

function tailscaleStatus() {
  const result = spawnSync(tailscaleCLI, ["status", "--json"], { encoding: "utf8" });
  if (result.status !== 0) {
    throw new Error(result.stderr.trim() || "Tailscale is not running.");
  }
  return JSON.parse(result.stdout);
}

async function main() {
  const config = JSON.parse(await readFile(configPath, "utf8"));
  const argument = process.argv.find((value, index) => index > 1 && value !== "--print") || config.galleryURL;
  const galleryURL = requestedGalleryURL(argument, config.allowedOrigins || []);
  const localDevelopment = galleryURL.protocol === "http:";
  const source = localDevelopment ? localAgentURL(config) : tailscaleSelfURL(tailscaleStatus());
  if (!source) throw new Error("Tailscale has no HTTPS name for this Mac.");

  const target = galleryBootstrapURL(galleryURL, source);
  if (process.argv.includes("--print")) {
    console.log(target);
    return;
  }

  const opened = spawnSync("open", [target], { encoding: "utf8" });
  if (opened.status !== 0) throw new Error(opened.stderr.trim() || "Could not open Private Reel.");
}

if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
  main().catch((error) => {
    console.error(error instanceof Error ? error.message : error);
    process.exitCode = 1;
  });
}
