#!/usr/bin/env node

'use strict';

/**
 * Background update checker for @evolvconsulting/evolv-coder-kit
 * Runs as a SessionStart hook to check for newer versions.
 * Non-blocking — exits 0 always, prints advisory message only.
 */

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');

const PACKAGE_NAME = '@evolvconsulting/evolv-coder-kit';
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
const STATE_FILE = path.join(os.homedir(), '.claude', 'evolv-coder-kit', '.update-check');

function readState() {
  try {
    if (fs.existsSync(STATE_FILE)) {
      return JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8'));
    }
  } catch {
    // Ignore read errors
  }
  return { lastCheck: 0, latestVersion: null };
}

function writeState(state) {
  try {
    const dir = path.dirname(STATE_FILE);
    fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(STATE_FILE, JSON.stringify(state), 'utf-8');
  } catch {
    // Ignore write errors
  }
}

function getInstalledVersion() {
  try {
    const pkgPath = path.resolve(__dirname, '..', 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
    return pkg.version;
  } catch {
    return null;
  }
}

function getLatestVersion() {
  try {
    const result = execSync(`npm view ${PACKAGE_NAME} version`, {
      timeout: 5000,
      encoding: 'utf-8',
      stdio: ['pipe', 'pipe', 'pipe'],
    });
    return result.trim();
  } catch {
    return null;
  }
}

function compareVersions(a, b) {
  const pa = a.split('.').map(Number);
  const pb = b.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    if ((pa[i] || 0) < (pb[i] || 0)) return -1;
    if ((pa[i] || 0) > (pb[i] || 0)) return 1;
  }
  return 0;
}

function extractYamlField(content, field) {
  const m = content.match(new RegExp(`^${field}:\\s*"?([^"\\n]+)"?`, 'm'));
  return m ? m[1].trim() : null;
}

function checkProjectVersion() {
  try {
    const catalogPath = path.join(process.cwd(), '.claude', 'project-catalog.yaml');
    if (!fs.existsSync(catalogPath)) return; // Not a managed project

    const content = fs.readFileSync(catalogPath, 'utf-8');
    const projVer = extractYamlField(content, 'template_version');
    if (!projVer) return;

    const globalPath = path.join(os.homedir(), '.claude', 'evolv-coder-kit', 'global-catalog.yaml');
    if (!fs.existsSync(globalPath)) return;

    const globalContent = fs.readFileSync(globalPath, 'utf-8');
    const globalVer = extractYamlField(globalContent, 'template_version');
    if (!globalVer) return;

    if (compareVersions(projVer, globalVer) < 0) {
      const useColor = process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb';
      const orange = useColor ? '\x1b[38;2;209;86;53m' : '';
      const bold = useColor ? '\x1b[1m' : '';
      const reset = useColor ? '\x1b[0m' : '';
      const arrow = useColor ? '\u2192' : '->';
      console.log(`${orange}[*]${reset} ${bold}Project outdated${reset}: templates ${projVer} ${arrow} ${globalVer}`);
      console.log(`${orange}[>]${reset} Run: /eck:update-project`);
    }
  } catch { /* non-blocking */ }
}

function main() {
  const state = readState();
  const now = Date.now();

  // Skip if checked recently
  if (now - state.lastCheck < CHECK_INTERVAL_MS) {
    process.exit(0);
  }

  const installed = getInstalledVersion();
  const latest = getLatestVersion();

  // Update state
  writeState({ lastCheck: now, latestVersion: latest });

  if (installed && latest && compareVersions(installed, latest) < 0) {
    const useColor = process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb';
    const orange = useColor ? '\x1b[38;2;209;86;53m' : '';
    const bold = useColor ? '\x1b[1m' : '';
    const reset = useColor ? '\x1b[0m' : '';
    const arrow = useColor ? '\u2192' : '->';
    console.log(`${orange}[*]${reset} ${bold}Update available${reset}: ${installed} ${arrow} ${latest}`);
    console.log(`${orange}[>]${reset} Run: npx ${PACKAGE_NAME} --global --overwrite`);
  }

  // Check if current project's templates are outdated vs global catalog
  checkProjectVersion();

  process.exit(0);
}

module.exports = { compareVersions, extractYamlField, checkProjectVersion };

if (require.main === module) {
  main();
}
