/**
 * studiograph folder command
 *
 * Subcommands:
 *   studiograph folder add <name>     — create a new folder
 *   studiograph folder list           — list all folders with entity counts
 *   studiograph folder rename <old> <new> — rename a folder
 *   studiograph folder remove <name>  — remove a folder (with confirmation)
 */
import { Command } from 'commander';
import { log, confirm } from '@clack/prompts';
import { existsSync } from 'fs';
import { join } from 'path';
import { Workspace } from '../../../core/workspace.js';
import { BaseGraphManager } from '../../../core/graph.js';
function requireWorkspace() {
    const workspace = new Workspace();
    if (!workspace.isWorkspace()) {
        console.error('Not a Studiograph workspace. Run `studiograph init` first.');
        return null;
    }
    return workspace;
}
// ─── add ──────────────────────────────────────────────────────────────────────
const addCommand = new Command('add')
    .description('Create a new folder')
    .argument('<name>', 'Folder name (kebab-case)')
    .option('-d, --description <desc>', 'Folder description')
    .action(async (name, opts) => {
    const workspace = requireWorkspace();
    if (!workspace) {
        process.exit(1);
        return;
    }
    // Validate name is kebab-case
    if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {
        log.error('Folder name must be kebab-case (e.g., "client-projects")');
        process.exit(1);
        return;
    }
    try {
        const repo = await workspace.registerRepo({
            name,
            description: opts.description,
        });
        log.success(`Folder "${repo.name}" created at ${repo.path}/`);
    }
    catch (err) {
        log.error(err instanceof Error ? err.message : 'Unknown error');
        process.exit(1);
    }
});
// ─── list ─────────────────────────────────────────────────────────────────────
const listCommand = new Command('list')
    .description('List all folders with entity counts')
    .action(async () => {
    const workspace = requireWorkspace();
    if (!workspace) {
        process.exit(1);
        return;
    }
    const config = await workspace.loadConfig();
    const repos = config.repos;
    if (repos.length === 0) {
        log.info('No folders. Run `studiograph folder add <name>` to create one.');
        return;
    }
    console.log('\nFolders\n');
    console.log('  Name                          Entities  Description');
    console.log('  ' + '\u2500'.repeat(72));
    for (const repo of repos) {
        let entityCount = 0;
        const repoPath = join(workspace.getWorkspacePath(), repo.path);
        if (existsSync(repoPath)) {
            try {
                const graph = new BaseGraphManager({
                    repoPath,
                    repoName: repo.name,
                    gitUser: { id: 'cli', name: 'cli', email: 'cli@studiograph.local' },
                });
                entityCount = graph.list().length;
            }
            catch { /* non-fatal */ }
        }
        const rname = repo.name.padEnd(30);
        const count = String(entityCount).padStart(4);
        const desc = repo.description || '';
        const suffix = repo.personal ? ' (personal)' : '';
        console.log(`  ${rname}  ${count}  ${desc}${suffix}`);
    }
    console.log('');
});
// ─── rename ───────────────────────────────────────────────────────────────────
const renameCommand = new Command('rename')
    .description('Rename a folder')
    .argument('<old-name>', 'Current folder name')
    .argument('<new-name>', 'New folder name (kebab-case)')
    .action(async (oldName, newName) => {
    const workspace = requireWorkspace();
    if (!workspace) {
        process.exit(1);
        return;
    }
    if (!/^[a-z0-9][a-z0-9-]*$/.test(newName)) {
        log.error('New name must be kebab-case (e.g., "client-projects")');
        process.exit(1);
        return;
    }
    const config = await workspace.loadConfig();
    const repo = config.repos.find(r => r.name === oldName);
    if (!repo) {
        log.error(`Folder "${oldName}" not found.`);
        process.exit(1);
        return;
    }
    if (config.repos.some(r => r.name === newName)) {
        log.error(`Folder "${newName}" already exists.`);
        process.exit(1);
        return;
    }
    const oldPath = join(workspace.getWorkspacePath(), repo.path);
    const newPath = join(workspace.getWorkspacePath(), newName);
    // Rename directory
    if (existsSync(oldPath)) {
        const { renameSync } = await import('fs');
        renameSync(oldPath, newPath);
    }
    // Update config
    repo.name = newName;
    repo.path = newName;
    workspace.writeConfig(config);
    // Update .studiograph marker in the repo
    const markerPath = join(newPath, '.studiograph');
    if (existsSync(markerPath)) {
        const { writeFileSync } = await import('fs');
        writeFileSync(markerPath, JSON.stringify({ repo_name: newName }, null, 2), 'utf-8');
    }
    log.success(`Folder renamed: "${oldName}" → "${newName}"`);
});
// ─── remove ───────────────────────────────────────────────────────────────────
const removeCommand = new Command('remove')
    .description('Remove a folder from the workspace')
    .argument('<name>', 'Folder name to remove')
    .option('--delete-files', 'Also delete the folder directory from disk')
    .action(async (name, opts) => {
    const workspace = requireWorkspace();
    if (!workspace) {
        process.exit(1);
        return;
    }
    const config = await workspace.loadConfig();
    const repoIndex = config.repos.findIndex(r => r.name === name);
    if (repoIndex === -1) {
        log.error(`Folder "${name}" not found.`);
        process.exit(1);
        return;
    }
    const repo = config.repos[repoIndex];
    const repoPath = join(workspace.getWorkspacePath(), repo.path);
    const yes = await confirm({
        message: opts.deleteFiles
            ? `Remove folder "${name}" and delete all files at ${repo.path}/?`
            : `Remove folder "${name}" from workspace config? (files at ${repo.path}/ will be kept)`,
    });
    if (!yes || typeof yes === 'symbol')
        return;
    // Remove from config
    config.repos.splice(repoIndex, 1);
    workspace.writeConfig(config);
    if (opts.deleteFiles && existsSync(repoPath)) {
        const { rmSync } = await import('fs');
        rmSync(repoPath, { recursive: true, force: true });
        log.success(`Folder "${name}" removed and files deleted.`);
    }
    else {
        log.success(`Folder "${name}" removed from config. Files at ${repo.path}/ were kept.`);
    }
});
// ─── parent command ───────────────────────────────────────────────────────────
export const folderCommand = new Command('folder')
    .description('Manage workspace folders')
    .addCommand(addCommand)
    .addCommand(listCommand)
    .addCommand(renameCommand)
    .addCommand(removeCommand);
//# sourceMappingURL=folder.js.map