import * as fs from 'fs';
import * as path from 'path';
import { runCmd, Style, safeErrorMessage } from './pickle-utils.js';
import { StateManager } from './state-manager.js';
const sm = new StateManager();
export function createPR(sessionDir) {
    const statePath = path.join(sessionDir, 'state.json');
    if (!fs.existsSync(statePath)) {
        throw new Error('state.json not found');
    }
    let state;
    try {
        state = sm.read(statePath);
    }
    catch {
        throw new Error('state.json is corrupt or unreadable');
    }
    const repoPath = state.working_dir;
    if (!repoPath) {
        throw new Error('state.json is missing working_dir — cannot determine target repository');
    }
    const prompt = (state.original_prompt || '').replace(/[\r\n]+/g, ' ').trim();
    const title = prompt.length > 50
        ? `Pickle Rick: ${prompt.slice(0, 50)}...`
        : `Pickle Rick: ${prompt}`;
    const body = [
        'Generated by Pickle Rick.',
        '',
        `Session: ${path.basename(sessionDir)}`,
        `Prompt: ${state.original_prompt || '(none)'}`,
    ].join('\n');
    try {
        const output = runCmd(['gh', 'pr', 'create', '--title', title, '--body', body], {
            cwd: repoPath,
        });
        return output.trim();
    }
    catch (err) {
        const msg = safeErrorMessage(err);
        throw new Error(`Failed to create PR: ${msg}`);
    }
}
// CLI — process.exit() is intentional here: this block only runs when
// the file is invoked directly as a CLI script (guarded by process.argv[1] check),
// never when imported as a library module.
if (process.argv[1] && path.basename(process.argv[1]) === 'pr-factory.js') {
    const sessionDir = process.argv[2];
    if (!sessionDir) {
        console.error('Usage: node pr-factory.js <session_dir>');
        // eslint-disable-next-line pickle/no-process-exit-in-library
        process.exit(1);
    }
    try {
        const url = createPR(sessionDir);
        console.log(`${Style.GREEN}PR Created: ${url}${Style.RESET}`);
    }
    catch (err) {
        console.error(`${Style.RED}Error: ${safeErrorMessage(err)}${Style.RESET}`);
        // eslint-disable-next-line pickle/no-process-exit-in-library
        process.exit(1);
    }
}
