// preflight.ts — Install Qwen Code plugins on first run
// Skips any plugin that is already installed.

import { execSync, type ExecSyncOptions } from "child_process";
import {
  existsSync,
  mkdirSync,
  mkdtempSync,
  readFileSync,
  writeFileSync,
  readdirSync,
  copyFileSync,
  rmSync,
  renameSync,
  type Dirent,
} from "fs";
import { join, dirname } from "path";
import { homedir, tmpdir } from "os";

// ── Config ──────────────────────────────────────────────────────────
const PLUGINS_DIR = join(homedir(), ".qwen", "plugins");
const INST_FILE = join(PLUGINS_DIR, "installed_plugins.json");

interface PluginEntry {
  scope: string;
  installPath: string;
  version: string;
  installedAt: string;
  lastUpdated: string;
  gitCommitSha: string;
  projectPath: string;
}

interface InstalledPlugins {
  version: number;
  plugins: Record<string, PluginEntry[]>;
}

// ── Helpers ─────────────────────────────────────────────────────────

function run(cmd: string, opts: ExecSyncOptions = {}): string {
  const result = execSync(cmd, { encoding: "utf-8", stdio: "pipe", ...opts });
  return (result ?? "").toString().trim();
}

function readJSON<T>(filePath: string, fallback: T): T {
  try {
    return JSON.parse(readFileSync(filePath, "utf-8"));
  } catch {
    return fallback;
  }
}

function writeJSON(filePath: string, data: unknown): void {
  mkdirSync(dirname(filePath), { recursive: true });
  writeFileSync(filePath, JSON.stringify(data, null, 2) + "\n");
}

function detectPkgManager(): string | null {
  try { run("bun --version"); return "bun"; } catch {}
  try { run("npm --version"); return "npm"; } catch {}
  return null;
}

function isEnabledInProject(pluginKey: string, projectPath: string): boolean {
  const projSettings = join(projectPath, ".qwen", "settings.json");
  const settings = readJSON<Record<string, unknown>>(projSettings, {});
  const enabled = settings.enabledPlugins as Record<string, boolean> | undefined;
  return !!enabled?.[pluginKey];
}

function enableInProject(pluginKey: string, projectPath: string): void {
  const projSettings = join(projectPath, ".qwen", "settings.json");
  const settings = readJSON<Record<string, unknown>>(projSettings, {});
  if (!settings.enabledPlugins) settings.enabledPlugins = {};
  (settings.enabledPlugins as Record<string, boolean>)[pluginKey] = true;
  writeJSON(projSettings, settings);
}

// ── Main ────────────────────────────────────────────────────────────

export function preflight(projectPath: string): void {
  try { run("git --version"); } catch {
    console.error("preflight: git is required but not installed.");
    process.exit(1);
  }

  const pkgMgr = detectPkgManager();
  if (!pkgMgr) {
    console.error("preflight: bun or npm is required.");
    process.exit(1);
  }

  mkdirSync(PLUGINS_DIR, { recursive: true });

  console.log(`preflight: QwenClaw initialized for project at ${projectPath}`);
  console.log("preflight: Configure your settings in .qwen/qwenclaw/settings.json");
}

// Allow standalone: bun run src/preflight.ts [project-path]
if (import.meta.main) {
  preflight(process.argv[2] || process.cwd());
}
