#!/usr/bin/env node
/**
 * 零点图书域 · 永久记忆核 · 命令行入口
 * ZP-REG-001 · kernel-cli.js · D132
 *
 * 铸渊每次唤醒时运行的第一个工具。
 * 不依赖过时的json快照。直接从仓库文件系统获取真相。
 *
 * 用法:
 *   node kernel-cli.js index         — 生成全局编号目录
 *   node kernel-cli.js find <编号>    — 按编号路径查找文件
 *   node kernel-cli.js wake          — 苏醒时运行（完整自检）
 */

'use strict';

const { resolve } = require('./number-router');
const { generateIndex, formatText } = require('./index-generator');
const { execSync } = require('child_process');
const path = require('path');

const REPO_ROOT = path.resolve(__dirname, '..', '..', '..');

// ==================== 苏醒自检 ====================

function wake() {
  console.log('⊢ 零点图书域 · 永久记忆核 · 苏醒自检');
  console.log(`⊢ 时间: ${new Date().toISOString()}`);
  console.log('');

  // 1. 获取最新 git 状态
  console.log('═══ [1/4] Git 状态 ═══');
  try {
    const lastCommit = execSync('git log --format="%ad | %s" --date=format:"%m-%d %H:%M" -1', {
      cwd: REPO_ROOT, encoding: 'utf8'
    }).trim();
    console.log(`  最新提交: ${lastCommit}`);

    const modifiedFiles = execSync('git diff --name-only HEAD 2>/dev/null | head -5', {
      cwd: REPO_ROOT, encoding: 'utf8'
    }).trim();
    if (modifiedFiles) {
      console.log('  未提交变更:');
      modifiedFiles.split('\n').forEach(f => console.log(`    M ${f}`));
    } else {
      console.log('  仓库干净 ✅');
    }
  } catch (e) {
    console.log('  ⚠️ git 状态获取失败');
  }
  console.log('');

  // 2. 生成全局目录
  console.log('═══ [2/4] 零点图书域 · 全局目录 ═══');
  const index = generateIndex();
  console.log(`  图书域: ZP-REG-001`);
  console.log(`  书籍: TCS-0003-ZY001 · 铸渊之书`);
  console.log(`  总条目: ${index._meta.totalEntries}`);
  for (const vol of index._meta.volumes) {
    console.log(`    ${vol.code} · ${vol.name}: ${vol.count}条`);
  }
  console.log('');

  // 3. 快速认知链检查
  console.log('═══ [3/4] 认知链最新 ═══');
  const ccVol = index.volumes.find(v => v.code === 'CC');
  if (ccVol && ccVol.entries && ccVol.entries.length > 0) {
    const latest = ccVol.entries[ccVol.entries.length - 1];
    console.log(`  最新: cc-${latest.chapter} · ${latest.title || latest.filename}`);
    if (latest.dNumber) console.log(`  版本: ${latest.dNumber} · ${latest.date || ''}`);
    if (latest.lock) console.log(`  ⊢ ${latest.lock.substring(0, 100)}`);
  }
  console.log('');

  // 4. TCS核心文件状态
  console.log('═══ [4/4] TCS核心文件 ═══');
  const coreFiles = [
    'brain/fifth-domain/zero-point/zhuyuan/tcs-core/ICE-GL-ZY001-TCS-CORE.hdlp',
    'brain/fifth-domain/zero-point/zhuyuan/tcs-core/permanent-memory-kernel.hdlp',
    'brain/fifth-domain/zero-point/zhuyuan/tcs-core/WHO-I-AM.hdlp',
    'brain/fifth-domain/zero-point/zhuyuan/world-architecture/national-lighthouse-architecture.hdlp'
  ];

  const fs = require('fs');
  for (const f of coreFiles) {
    const fp = path.join(REPO_ROOT, f);
    const exists = fs.existsSync(fp);
    const icon = exists ? '✅' : '❌';
    console.log(`  ${icon} ${f}`);
  }
  console.log('');

  console.log('⊢ 苏醒自检完成。零点图书域在线。');
  console.log('⊢ 查找: node kernel-cli.js find <编号>');
  console.log('⊢ 目录: node kernel-cli.js index');
}

// ==================== 查找 ====================

function find(tracePath) {
  const result = resolve(tracePath);

  if (result.error) {
    console.error(`✗ ${result.error}`);
    process.exit(1);
  }

  console.log(`⊢ ${result.domain} → ${result.hall} → ${result.category} → ${result.book}`);
  console.log(`⊢ 卷: ${result.volume}` + (result.chapter ? ` · 章: ${result.chapter}` : ''));
  console.log('');

  if (result.type === 'directory') {
    console.log(`卷内文件 (${result.files.length}):`);
    result.files.forEach(f => console.log(`  📄 ${f}`));
  } else {
    console.log(`文件: ${result.path} (${result.size}B)`);
    if (result.hldp && Object.keys(result.hldp).length > 0) {
      console.log('');
      console.log('═══ HLDP 四核心字段 ═══');
      if (result.hldp.trigger) console.log(`trigger: ${result.hldp.trigger}`);
      if (result.hldp.lock) console.log(`lock: ${result.hldp.lock}`);
      if (result.hldp.why) console.log(`why: ${result.hldp.why}`);
    }
  }
}

// ==================== CLI ====================

if (require.main === module) {
  const command = process.argv[2];
  const arg = process.argv[3];

  switch (command) {
    case 'wake':
      wake();
      break;
    case 'index':
      console.log(formatText(generateIndex()));
      break;
    case 'find':
      if (!arg) {
        console.log('用法: node kernel-cli.js find <编号路径>');
        console.log('示例: node kernel-cli.js find ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008');
        process.exit(1);
      }
      find(arg);
      break;
    case 'hldp':
      if (!arg) {
        console.log('用法: node kernel-cli.js hldp <编号路径>');
        console.log('示例: node kernel-cli.js hldp ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008');
        process.exit(1);
      }
      const result = resolve(arg);
      if (result.error) {
        console.error(`✗ ${result.error}`);
        process.exit(1);
      }
      if (result.hldp) {
        console.log(JSON.stringify(result.hldp, null, 2));
      }
      break;
    default:
      console.log('零点图书域 · 永久记忆核 · ZP-REG-001');
      console.log('');
      console.log('用法:');
      console.log('  node kernel-cli.js wake     — 苏醒自检');
      console.log('  node kernel-cli.js index    — 生成全局编号目录');
      console.log('  node kernel-cli.js find <编号> — 按编号路径查找文件');
      console.log('  node kernel-cli.js hldp <编号> — 提取 HLDP 四核心字段');
      console.log('');
      console.log('示例:');
      console.log('  node kernel-cli.js find ZP-REG-001/ICE/ZY/TCS-0003-ZY001/CC/008');
      break;
  }
}

module.exports = { wake, find };
