import { readFileSync, existsSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const MANIFEST = resolve(__dirname, '..', 'dev-indices.json');

function usage() {
    console.error('Usage: npm run dx <id>');
    console.error('Looks up element by dev-index in dev-indices.json.');
    process.exit(2);
}

const arg = process.argv[2];
if (!arg || !/^\d+$/.test(arg)) usage();
const id = arg;

if (!existsSync(MANIFEST)) {
    console.error(`dev-indices.json not found at ${MANIFEST}`);
    console.error('Run "npm run dev" first to generate the manifest.');
    process.exit(1);
}

const manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));

if (manifest.entries?.[id]) {
    const e = manifest.entries[id];
    console.log(`#${id} → ${e.file}:${e.line}`);
    console.log(`${e.tag}${e.text ? ` "${e.text}"` : ''}`);
    console.log(`parent: ${e.parentChain.join(' > ')}`);
    console.log(`signature: ${e.signature}`);
    console.log(`created: ${e.createdAt.split('T')[0]}`);
    process.exit(0);
}

if (manifest.deleted?.[id]) {
    const d = manifest.deleted[id];
    console.log(`#${id} (DELETED at ${d.deletedAt.split('T')[0]})`);
    console.log(`last seen in ${d.lastFile}`);
    console.log(`last signature: ${d.lastSignature}`);
    process.exit(0);
}

console.error(`#${id} not found in manifest.`);
process.exit(1);
