/**
 * studiograph orphans
 *
 * Finds entities with zero inbound wikilink references ("orphans")
 * and optionally tombstones or deletes them.
 */
import { Command } from 'commander';
import { Workspace } from '../../core/workspace.js';
import { WorkspaceManager } from '../../core/workspace-manager.js';
import { intro, outro, spinner, confirm } from '@clack/prompts';
import { findOrphans } from '../../services/orphan-service.js';
export const orphansCommand = new Command('orphans')
    .description('Find entities with zero inbound references')
    .option('--entity-types <types>', 'Comma-separated entity types to check (e.g. person,client)')
    .option('--min-age <days>', 'Only flag entities older than N days', parseInt)
    .option('--repos <repos>', 'Comma-separated repo names to scan')
    .option('--delete', 'Delete orphan entity files')
    .option('--dry-run', 'Preview changes without modifying anything')
    .action(async (options) => {
    intro('Studiograph Orphans');
    const s = spinner();
    s.start('Loading workspace');
    try {
        const workspace = new Workspace();
        if (!workspace.isWorkspace()) {
            console.error('❌ Not a Studiograph workspace. Run `studiograph init` first.');
            process.exit(1);
        }
        const config = await workspace.loadConfig();
        const gitUser = { id: 'system', name: 'system', email: 'system@local' };
        const manager = new WorkspaceManager(process.cwd(), config, gitUser);
        s.message('Scanning for orphans');
        const filters = {
            entityTypes: options.entityTypes?.split(',').map((t) => t.trim()),
            minAgeDays: options.minAge,
            repos: options.repos?.split(',').map((r) => r.trim()),
        };
        const result = findOrphans(manager, filters);
        s.stop('Scan complete');
        if (result.totalOrphans === 0) {
            outro(`✅ No orphans found (scanned ${result.totalScanned} entities)`);
            return;
        }
        // Group by entity type
        const grouped = new Map();
        for (const orphan of result.orphans) {
            const key = orphan.entityType;
            if (!grouped.has(key))
                grouped.set(key, []);
            grouped.get(key).push(orphan);
        }
        console.log('');
        console.log(`Found ${result.totalOrphans} orphans (of ${result.totalScanned} scanned):\n`);
        for (const [entityType, typeOrphans] of grouped.entries()) {
            console.log(`${entityType.toUpperCase()} (${typeOrphans.length})`);
            const examples = typeOrphans.slice(0, 10);
            for (const orphan of examples) {
                const name = orphan.name || orphan.entityId;
                const age = orphan.createdAt
                    ? `created ${orphan.createdAt}`
                    : '';
                console.log(`  - ${orphan.repo}/${orphan.entityType}/${orphan.entityId}${age ? `  (${age})` : ''}`);
            }
            if (typeOrphans.length > 10) {
                console.log(`  ... and ${typeOrphans.length - 10} more`);
            }
            console.log('');
        }
        // Delete action
        if (options.delete) {
            if (options.dryRun) {
                console.log(`[dry-run] Would delete ${result.totalOrphans} orphan(s)`);
                outro('Dry run complete');
                return;
            }
            const shouldProceed = await confirm({
                message: `Delete ${result.totalOrphans} orphan(s)?`,
                initialValue: false,
            });
            if (!shouldProceed || typeof shouldProceed === 'symbol') {
                outro('Cancelled');
                return;
            }
            const actionSpinner = spinner();
            actionSpinner.start(`Deleting ${result.totalOrphans} orphans...`);
            let deleted = 0;
            for (const orphan of result.orphans) {
                try {
                    const graph = manager.getGraph(orphan.repo);
                    await graph.delete(orphan.entityType, orphan.entityId);
                    deleted++;
                }
                catch {
                    // Entity might already be gone
                }
            }
            actionSpinner.stop('Done');
            console.log(`\nDeleted ${deleted} entities`);
        }
        outro('Orphan scan complete');
    }
    catch (error) {
        s.stop('Error');
        console.error('Failed to scan for orphans:', error instanceof Error ? error.message : error);
        process.exit(1);
    }
});
//# sourceMappingURL=orphans.js.map