#!/usr/bin/env node

// scripts/postinstall.ts
import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, readdirSync } from "fs";
import { homedir, tmpdir } from "os";
import { join } from "path";
var LOG_FILE = join(tmpdir(), "opencode-orchestrator.log");
function log(message, data) {
  try {
    const timestamp = (/* @__PURE__ */ new Date()).toISOString();
    const entry = `[${timestamp}] [postinstall] ${message} ${data ? JSON.stringify(data) : ""}
`;
    appendFileSync(LOG_FILE, entry);
  } catch {
  }
}
function formatError(err, context) {
  if (err instanceof Error) {
    const nodeErr = err;
    if (nodeErr.code === "EACCES" || nodeErr.code === "EPERM") {
      return `Permission denied: Cannot ${context}. Try running as administrator.`;
    }
    if (nodeErr.code === "ENOENT") {
      return `File not found while trying to ${context}.`;
    }
    if (err instanceof SyntaxError) {
      return `JSON syntax error while trying to ${context}: ${err.message}.`;
    }
    if (nodeErr.code === "EIO") {
      return `File lock error: Cannot ${context}. Please close OpenCode and try again.`;
    }
    if (nodeErr.code === "ENOSPC") {
      return `Disk full: Cannot ${context}. Free up disk space and try again.`;
    }
    if (nodeErr.code === "EROFS") {
      return `Read-only filesystem: Cannot ${context}.`;
    }
    return `Failed to ${context}: ${err.message}`;
  }
  return `Failed to ${context}: ${String(err)}`;
}
var PLUGIN_NAME = "opencode-orchestrator";
function getConfigPaths() {
  const paths = [];
  if (process.env.XDG_CONFIG_HOME) {
    paths.push(join(process.env.XDG_CONFIG_HOME, "opencode"));
  }
  if (process.platform === "win32") {
    const appDataPath = process.env.APPDATA || join(homedir(), "AppData", "Roaming");
    paths.push(join(appDataPath, "opencode"));
    const dotConfigPath = join(homedir(), ".config", "opencode");
    if (!paths.includes(dotConfigPath)) {
      paths.push(dotConfigPath);
    }
  } else {
    paths.push(join(homedir(), ".config", "opencode"));
  }
  return paths;
}
function createBackup(configFile) {
  try {
    if (!existsSync(configFile)) return true;
    const backupFile = `${configFile}.backup.${Date.now()}`;
    const content = readFileSync(configFile, "utf-8");
    writeFileSync(backupFile, content);
    log("Backup created", { backupFile });
    return true;
  } catch (err) {
    log("Backup creation failed", { error: String(err) });
    return false;
  }
}
function registerInConfig(configDir) {
  const configFile = join(configDir, "opencode.json");
  try {
    if (!existsSync(configDir)) {
      mkdirSync(configDir, { recursive: true });
      log("Config directory created", { configDir });
    }
    let config = {};
    let isNewFile = false;
    if (existsSync(configFile)) {
      try {
        const content = readFileSync(configFile, "utf-8").trim();
        if (!content) {
          config = {};
          log("Empty config file detected, creating new config");
        } else {
          config = JSON.parse(content);
          log("Existing config loaded", { keys: Object.keys(config) });
        }
      } catch (parseErr) {
        log("Config parse error, creating backup", { error: String(parseErr) });
        createBackup(configFile);
        config = {};
      }
    } else {
      isNewFile = true;
      log("No config file found, creating new");
    }
    if (!config.plugin) {
      config.plugin = [];
    }
    if (!Array.isArray(config.plugin)) {
      log("Invalid plugin field (not array), resetting", { current: config.plugin });
      config.plugin = [];
    }
    const hasPlugin = config.plugin.some((p) => {
      if (typeof p !== "string") return false;
      return p === PLUGIN_NAME || p.includes(PLUGIN_NAME);
    });
    if (hasPlugin) {
      log("Plugin already registered", { plugins: config.plugin });
      return false;
    }
    config.plugin.push(PLUGIN_NAME);
    if (!config.$schema) {
      config.$schema = "https://opencode.ai/config.json";
    }
    if (!isNewFile) {
      createBackup(configFile);
    }
    const configContent = JSON.stringify(config, null, 2) + "\n";
    writeFileSync(configFile, configContent, { encoding: "utf-8", mode: 420 });
    log("Config written successfully", {
      configFile,
      isNewFile,
      plugins: config.plugin,
      allKeys: Object.keys(config)
    });
    return true;
  } catch (err) {
    log("registerInConfig failed", {
      error: String(err),
      code: err.code
    });
    return false;
  }
}
try {
  console.log("\u{1F3AF} OpenCode Orchestrator - Installing...");
  console.log("");
  log("Installation started", { platform: process.platform, node: process.version });
  const configPaths = getConfigPaths();
  log("Config paths to check", configPaths);
  let registered = false;
  let alreadyRegistered = false;
  let configsChecked = 0;
  let registeredPath = "";
  for (const configDir of configPaths) {
    const configFile = join(configDir, "opencode.json");
    configsChecked++;
    if (existsSync(configFile)) {
      try {
        const content = readFileSync(configFile, "utf-8").trim();
        if (content) {
          const config = JSON.parse(content);
          if (config.plugin?.some((p) => p.includes(PLUGIN_NAME))) {
            console.log(`\u2705 Already registered in: ${configFile}`);
            log("Already registered", { configFile });
            alreadyRegistered = true;
            registeredPath = configFile;
            continue;
          }
        }
      } catch (err) {
        log("Parse error checking existing config", { configFile, error: String(err) });
      }
    }
    if (registerInConfig(configDir)) {
      console.log(`\u2705 Plugin registered in: ${configFile}`);
      console.log("   \u{1F4DD} Your existing settings have been preserved");
      try {
        const files = readdirSync(configDir);
        const hasBackup = files.some((f) => f.startsWith("opencode.json.backup."));
        if (hasBackup) {
          console.log("   \u{1F4BE} Backup created for safety");
        }
      } catch {
      }
      log("Plugin registered successfully", { configFile });
      registered = true;
      registeredPath = configFile;
      break;
    }
  }
  console.log("");
  if (registered) {
    console.log("\u2705 Installation successful!");
    console.log(`   Config file: ${registeredPath}`);
  } else if (alreadyRegistered) {
    console.log("\u2705 Plugin already installed!");
    console.log(`   Config file: ${registeredPath}`);
  } else {
    console.log("\u26A0\uFE0F  Could not register plugin automatically.");
    console.log("");
    console.log("   Please manually add to your OpenCode config:");
    console.log(`   ${configPaths[0]}/opencode.json`);
    console.log("");
    console.log("   Add this line:");
    console.log(`   "plugin": ["${PLUGIN_NAME}"]`);
    console.log("");
    log("Failed to register plugin in any location", { configsChecked, paths: configPaths });
  }
  console.log("");
  console.log("\u{1F680} Next steps:");
  console.log("   1. Restart OpenCode");
  console.log("   2. Try /task command in your project");
  console.log("");
  log("Installation completed", {
    registered,
    alreadyRegistered,
    configsChecked,
    registeredPath
  });
} catch (error) {
  console.log("");
  console.error("\u274C Installation error:");
  console.error("   " + formatError(error, "register plugin"));
  console.log("");
  console.log("   Please report this issue at:");
  console.log("   https://github.com/agnusdei1207/opencode-orchestrator/issues");
  console.log("");
  log("Installation error", { error: String(error), stack: error instanceof Error ? error.stack : void 0 });
  process.exit(0);
}
