import path from 'node:path';
import { createInterface } from 'node:readline';
import { parsePositiveInt } from '../cli-validation.js';
import { writeStream } from '../utils.js';
import { GitCoordinateVerificationRequestV1Schema, verifyGitCoordinates, } from './coordinates.js';
async function* readRequests() {
    const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
    let lineNumber = 0;
    try {
        for await (const line of lines) {
            lineNumber++;
            if (line.length > 1_048_576) {
                throw new Error(`Invalid NDJSON on stdin line ${lineNumber}: the line exceeds 1048576 bytes.`);
            }
            if (!line.trim())
                continue;
            let parsed;
            try {
                parsed = JSON.parse(line);
            }
            catch (error) {
                throw new Error(`Invalid NDJSON on stdin line ${lineNumber}: ${error instanceof Error ? error.message : String(error)}`);
            }
            const request = GitCoordinateVerificationRequestV1Schema.safeParse(parsed);
            if (!request.success) {
                throw new Error(`Invalid coordinate request on stdin line ${lineNumber}: ${request.error.message}`);
            }
            yield request.data;
        }
    }
    finally {
        lines.close();
    }
}
function optionalPositive(value, fallback, label) {
    return value === undefined ? undefined : parsePositiveInt(value, fallback, label);
}
/** Register the body-free Git-native coordinate verification stream. */
export function registerCoordinateVerificationCommand(code) {
    const command = code
        .command('coordinate-verify')
        .description('Verify Git OID/path/span coordinates from NDJSON without emitting source')
        .requiredOption('--path <repo-root>', 'repository root')
        .option('--ref <ref>', 'optionally bind every coordinate to one pinned commit')
        .option('--max-requests <n>', 'maximum NDJSON requests')
        .option('--max-blob-bytes <n>', 'maximum bytes read from one blob')
        .option('--max-blob-lines <n>', 'maximum lines read from one blob')
        .option('--max-total-blob-bytes <n>', 'maximum unique blob bytes read')
        .option('--max-batch-bytes <n>', 'maximum object bytes read by one Git batch')
        .option('--require-complete', 'exit nonzero when the footer reports incomplete coverage');
    command.action(async (options) => {
        try {
            const maxRequests = optionalPositive(options.maxRequests, 10_000, '--max-requests');
            const maxBlobBytes = optionalPositive(options.maxBlobBytes, 2_097_152, '--max-blob-bytes');
            const maxBlobLines = optionalPositive(options.maxBlobLines, 25_000, '--max-blob-lines');
            const maxTotalBlobBytes = optionalPositive(options.maxTotalBlobBytes, 268_435_456, '--max-total-blob-bytes');
            const maxBatchBytes = optionalPositive(options.maxBatchBytes, 33_554_432, '--max-batch-bytes');
            const request = {
                repoPath: path.resolve(options.path),
                ...(options.ref ? { ref: options.ref } : {}),
                ...(maxRequests !== undefined ? { maxRequests } : {}),
                ...(maxBlobBytes !== undefined ? { maxBlobBytes } : {}),
                ...(maxBlobLines !== undefined ? { maxBlobLines } : {}),
                ...(maxTotalBlobBytes !== undefined ? { maxTotalBlobBytes } : {}),
                ...(maxBatchBytes !== undefined ? { maxBatchBytes } : {}),
            };
            let complete = false;
            for await (const event of verifyGitCoordinates(readRequests(), request)) {
                await writeStream(process.stdout, `${JSON.stringify(event)}\n`);
                if (event.type === 'footer')
                    complete = event.complete;
            }
            if (options.requireComplete && !complete)
                process.exitCode = 1;
        }
        catch (error) {
            process.exitCode = 1;
            await writeStream(process.stderr, `Error: ${error instanceof Error ? error.message : String(error)}\n`);
        }
    });
}
//# sourceMappingURL=coordinates-command.js.map