#!/usr/bin/env node
"use strict";

// ClawCross LLM CLI wrapper
// Detects CLAWCROSS_HOME/CLAWCROSS_CONFIG_DIR the same way bin/clawcross.js does,
// then delegates to the Python CLI.

const { spawnSync } = require("node:child_process");
const path = require("node:path");

const root = path.resolve(__dirname, "..");

function getClawcrossHome() {
  return process.env.CLAWCROSS_HOME || path.join(require("os").homedir(), ".clawcross");
}

function isLegacyMode() {
  const value = (process.env.CLAWCROSS_USE_LEGACY_PATHS || "").trim().toLowerCase();
  return ["1", "true", "yes", "on"].includes(value);
}

function applyRuntimeEnv() {
  const legacy = isLegacyMode();
  const home = legacy ? root : getClawcrossHome();
  process.env.CLAWCROSS_HOME = home;
  process.env.CLAWCROSS_CONFIG_DIR = process.env.CLAWCROSS_CONFIG_DIR || (legacy ? path.join(root, "config") : path.join(home, "config"));
}

function firstExisting(candidates) {
  for (const candidate of candidates) {
    if (candidate && require("node:fs").existsSync(candidate)) {
      return candidate;
    }
  }
  return null;
}

function loadDotEnv(filePath) {
  if (!require("node:fs").existsSync(filePath)) {
    return {};
  }
  const values = {};
  for (const rawLine of require("node:fs").readFileSync(filePath, "utf8").split(/\r?\n/)) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#") || !line.includes("=")) {
      continue;
    }
    const index = line.indexOf("=");
    const key = line.slice(0, index).trim();
    let value = line.slice(index + 1).trim();
    if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
      value = value.slice(1, -1);
    }
    if (key) {
      values[key] = value;
    }
  }
  return values;
}

applyRuntimeEnv();

const venvDir = process.env.CLAWCROSS_VENV_DIR || (
  isLegacyMode() ? path.join(root, ".venv") : path.join(process.env.CLAWCROSS_HOME, "venv")
);

const python = firstExisting([
  process.platform === "win32" ? path.join(venvDir, "Scripts", "python.exe") : null,
  path.join(venvDir, "bin", "python"),
  process.platform === "win32" ? path.join(root, ".venv", "Scripts", "python.exe") : null,
  path.join(root, ".venv", "bin", "python"),
]) || process.env.PYTHON || (process.platform === "win32" ? "python" : "python3");

const configDir = process.env.CLAWCROSS_CONFIG_DIR;
const envPath = firstExisting([
  path.join(configDir, ".env"),
  path.join(root, "config", ".env"),
]);

loadDotEnv(envPath || path.join(configDir, ".env"));

// Try to find clawcross_cli in various locations
const possibleRoots = [
  process.env.CLAWCROSS_WORKSPACE_DIR,
  process.env.CLAWCROSS_HOME,
  path.join(process.env.HOME || require("os").homedir(), ".clawcross", "workspace"),
  root,
].filter(Boolean);

const clawcrossCliRoot = firstExisting(
  possibleRoots.flatMap(r => [
    path.join(r, "skills", "ClawCross", "clawcross_cli"),
    path.join(r, "clawcross_cli"),
  ])
);

if (!clawcrossCliRoot || !require("node:fs").existsSync(clawcrossCliRoot)) {
  console.error("clawcross-llm: cannot find clawcross_cli directory.");
  console.error("Searched in:", possibleRoots);
  process.exit(1);
}

const args = process.argv.slice(2);

const result = spawnSync(python, ["-m", "clawcross_cli.main", ...args], {
  stdio: "inherit",
  env: { ...process.env, CLAWCROSS_CONFIG_DIR: configDir },
  cwd: process.cwd(),
});

process.exit(result.status === null ? 1 : result.status);
