#!/usr/bin/env node
// scripts/postinstall.js
// Runs after npm install -g @lifeaitools/clauth
// On Windows: writes watchdog.ps1 to %APPDATA%\clauth\ and registers
// the Task Scheduler job via UAC elevation.

import fs from "fs";
import path from "path";
import os from "os";
import { fileURLToPath } from "url";
import { spawnSync } from "child_process";

const __dirname  = path.dirname(fileURLToPath(import.meta.url));
const APPDATA    = process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
const CLAUTH_DIR = path.join(APPDATA, "clauth");
const DEST_PS1   = path.join(CLAUTH_DIR, "watchdog.ps1");
const SOURCE_PS1 = path.join(__dirname, "..", "cli", "assets", "watchdog.ps1");
const PS_EXE     = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe";
const TASK_NAME  = "ClautWatchdog";

const CONFIG_DIR = os.platform() === "win32"
  ? path.join(APPDATA, "clauth-nodejs", "Config")
  : path.join(os.homedir(), ".config", "clauth-nodejs");

let version = "1.0.0";
try {
  const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8"));
  version = pkg.version;
} catch {}

// ----------------------------------------------------------------
// Watchdog helpers (Windows only)
// ----------------------------------------------------------------

function writeWatchdogScript() {
  try {
    fs.mkdirSync(CLAUTH_DIR, { recursive: true });
    fs.copyFileSync(SOURCE_PS1, DEST_PS1);
    return true;
  } catch (err) {
    console.log(`  ! Could not write watchdog script: ${err.message}`);
    return false;
  }
}

function isWatchdogRegistered() {
  try {
    const r = spawnSync(PS_EXE, [
      "-NoProfile", "-Command",
      `(Get-ScheduledTask -TaskName '${TASK_NAME}' -ErrorAction SilentlyContinue) -ne $null`,
    ], { encoding: "utf8", stdio: ["pipe","pipe","pipe"], timeout: 5000 });
    return (r.stdout || "").trim().toLowerCase() === "true";
  } catch { return false; }
}

function registerWatchdog() {
  const escaped = DEST_PS1.replace(/'/g, "''");
  const psCmd = [
    `$a = New-ScheduledTaskAction -Execute 'powershell.exe'`,
    ` -Argument '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File \\"${escaped}\\"';`,
    `$t = New-ScheduledTaskTrigger -AtLogOn;`,
    `$s = New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0 -RestartCount 3`,
    ` -RestartInterval (New-TimeSpan -Minutes 1) -MultipleInstances IgnoreNew;`,
    `Unregister-ScheduledTask -TaskName '${TASK_NAME}' -Confirm:$false -ErrorAction SilentlyContinue;`,
    `Register-ScheduledTask -TaskName '${TASK_NAME}' -Action $a -Trigger $t`,
    ` -Settings $s -RunLevel Highest -Description 'clauth daemon watchdog';`,
  ].join(" ");

  // Try direct first (works if already running as Administrator)
  const direct = spawnSync(PS_EXE, [
    "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", psCmd,
  ], { encoding: "utf8", stdio: ["pipe","pipe","pipe"], timeout: 10000 });

  if (direct.status === 0) return "ok";

  // Trigger UAC elevation — opens the Windows approval dialog
  const inner = psCmd.replace(/"/g, '\\"');
  const elevated = spawnSync(PS_EXE, [
    "-NoProfile", "-Command",
    `Start-Process '${PS_EXE}' -Verb RunAs -Wait -ArgumentList '-NoProfile -ExecutionPolicy Bypass -Command "${inner}"'`,
  ], { stdio: "inherit", encoding: "utf8", timeout: 60000 });

  return elevated.status === 0 ? "ok" : "denied";
}

function startWatchdog() {
  spawnSync(PS_EXE, [
    "-NoProfile", "-Command",
    `Start-ScheduledTask -TaskName '${TASK_NAME}' -ErrorAction SilentlyContinue`,
  ], { stdio: "pipe", timeout: 5000 });
}

function installCodevelopTerminalProfiles() {
  const cli = path.join(__dirname, "..", "cli", "index.js");
  const result = spawnSync(process.execPath, [
    cli,
    "codevelop",
    "install-terminal",
    "--repo",
    "C:\\Dev\\regen-root",
  ], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 10000 });

  if (result.status === 0) {
    console.log("  ✓ Co-development Windows Terminal profiles installed");
  } else {
    const msg = (result.stderr || result.stdout || "").trim();
    console.log(`  ! Co-development terminal profile install skipped${msg ? `: ${msg}` : ""}`);
    console.log("    Install later with: clauth codevelop install-terminal --repo C:\\Dev\\regen-root");
  }
}

// ----------------------------------------------------------------
// Main
// ----------------------------------------------------------------

async function main() {
  const configPath = path.join(CONFIG_DIR, "config.json");
  const isUpgrade  = fs.existsSync(configPath);

  if (isUpgrade) {
    console.log(`\n  \u2713 clauth upgraded to v${version}`);
    console.log(`  \u2713 Config preserved at ${CONFIG_DIR}`);
    try {
      const controller = new AbortController();
      const to = setTimeout(() => controller.abort(), 2000);
      const res = await fetch("http://127.0.0.1:52437/ping", { signal: controller.signal });
      clearTimeout(to);
      if (res.ok) console.log("  \u21BB Daemon running \u2014 restart: clauth serve restart");
    } catch {
      console.log("  \u25CB Daemon not running");
    }
  } else {
    console.log(`\n  Welcome to clauth v${version}!`);
    console.log("  Run 'clauth install' to set up your vault");
  }

  // Windows: register watchdog on fresh install; refresh script on upgrade
  if (os.platform() === "win32") {
    const registered = isWatchdogRegistered();
    if (!registered) {
      console.log("\n  Setting up auto-restart watchdog...");
      console.log("  Windows will ask for administrator approval \u2014 please click Yes.\n");
      if (writeWatchdogScript()) {
        const result = registerWatchdog();
        if (result === "ok") {
          startWatchdog();
          console.log("  \u2713 Watchdog registered and started (Task: ClautWatchdog)");
          console.log(`  \u2713 Script: ${DEST_PS1}`);
        } else {
          console.log("  ! Watchdog registration skipped (approval denied).");
          console.log("    Install later with: clauth watchdog install");
        }
      }
    } else {
      writeWatchdogScript(); // refresh script on upgrade
      console.log("  \u2713 Watchdog script updated");
    }
    installCodevelopTerminalProfiles();
  }

  console.log("  Run 'clauth doctor' to verify installation\n");
}

main().catch(() => {});
