import { Args, Command, Flags } from '@oclif/core';
import chalk from 'chalk';
import { unifiedDiff } from '../../origin/domain/diff.js';
import { discoverOrigins } from '../../origin/domain/origin-file.js';
export default class OriginDiff extends Command {
    static args = {
        pathspec: Args.string({
            description: 'Optional file or directory. Defaults to recursive cwd scan.',
            required: false,
        }),
    };
    static description = 'Print a unified diff of each `.origin` proposal against its current file.';
    static examples = [
        '<%= config.bin %> origin diff',
        '<%= config.bin %> origin diff backend/foo.ts',
        '<%= config.bin %> origin diff --json',
    ];
    static flags = {
        json: Flags.boolean({
            default: false,
            description: 'Emit machine-readable JSON instead of human text.',
        }),
    };
    async run() {
        const { args, flags } = await this.parse(OriginDiff);
        const origins = discoverOrigins(args.pathspec);
        const diffs = origins.map((entry) => ({
            current: entry.current,
            origin: entry.origin,
            patch: unifiedDiff(entry.current),
        }));
        if (flags.json) {
            this.log(JSON.stringify({ count: diffs.length, diffs }, null, 2));
            return;
        }
        if (diffs.length === 0) {
            this.log('No origin files to diff.');
            return;
        }
        const useColor = Boolean(process.stdout.isTTY);
        for (const entry of diffs) {
            this.log(chalk.bold(`=== ${entry.current} ===`));
            this.log(useColor ? colourise(entry.patch) : entry.patch);
            this.log('');
        }
    }
}
function colourise(patch) {
    return patch
        .split('\n')
        .map((line) => {
        if (line.startsWith('+++') || line.startsWith('---')) {
            return chalk.bold(line);
        }
        if (line.startsWith('+'))
            return chalk.green(line);
        if (line.startsWith('-'))
            return chalk.red(line);
        if (line.startsWith('@@'))
            return chalk.cyan(line);
        return line;
    })
        .join('\n');
}
