#!/usr/bin/env tsx
import { createDb } from './schema.js';

const args = process.argv.slice(2);
const command = args[0];

function main(): void {
  const db = createDb('arch.db');

  switch (command) {
    case 'stats':
      printStats(db);
      break;
    case 'modules':
      printModules(db);
      break;
    case 'symbols':
      printSymbols(db, args[1]);
      break;
    case 'deps':
      printDependencies(db, args[1]);
      break;
    case 'violations':
      printViolations(db);
      break;
    case 'sql':
      printSql(db, args[1]);
      break;
    default:
      console.log(`Usage: arch-query <command> [args]
Commands:
  stats           显示统计信息
  modules         列出所有模块
  symbols <name>  查询符号
  deps <module>   查模块依赖
  violations      查架构违规
  sql <SQL>       自定义 SQL 查询`);
  }

  db.close();
}

function printStats(db: ReturnType<typeof createDb>): void {
  const modules = (db.prepare('SELECT COUNT(*) as c FROM modules').get() as { c: number }).c;
  const symbols = (db.prepare('SELECT COUNT(*) as c FROM symbols').get() as { c: number }).c;
  const calls = (db.prepare('SELECT COUNT(*) as c FROM calls').get() as { c: number }).c;
  const deps = (db.prepare('SELECT COUNT(*) as c FROM dependencies').get() as { c: number }).c;
  console.log(`模块: ${modules}\n符号: ${symbols}\n调用: ${calls}\n依赖: ${deps}`);
}

function printModules(db: ReturnType<typeof createDb>): void {
  const rows = db.prepare('SELECT name, language, service, type FROM modules ORDER BY name').all();
  rows.forEach((r) => console.log(r));
}

function printSymbols(db: ReturnType<typeof createDb>, name: string | undefined): void {
  if (!name) {
    console.log('Usage: arch-query symbols <name>');
    return;
  }
  const rows = db.prepare('SELECT * FROM symbols WHERE name LIKE ?').all(`%${name}%`);
  rows.forEach((r) => console.log(r));
}

function printDependencies(db: ReturnType<typeof createDb>, module: string | undefined): void {
  if (!module) {
    console.log('Usage: arch-query deps <module>');
    return;
  }
  const rows = db.prepare(`
    SELECT m2.name as depends_on FROM dependencies d
    JOIN modules m1 ON d.source_module_id = m1.id
    JOIN modules m2 ON d.target_module_id = m2.id
    WHERE m1.name = ?
  `).all(module);
  rows.forEach((r) => console.log(r));
}

function printViolations(db: ReturnType<typeof createDb>): void {
  // 骨架：检查长文件、未校验权限的 Action 等
  console.log('骨架实现：P1 后期补全违规检测');
}

function printSql(db: ReturnType<typeof createDb>, sql: string | undefined): void {
  if (!sql) {
    console.log('Usage: arch-query sql "<SQL>"');
    return;
  }
  const rows = db.prepare(sql).all();
  rows.forEach((r) => console.log(r));
}

main();