var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import * as fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import pc from 'picocolors';
import { execGitShallowClone, isGitInstalled } from '../../core/file/gitCommand.js';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import Spinner from '../cliSpinner.js';
import { runDefaultAction } from './defaultAction.js';
export const runRemoteAction = (repoUrl_1, options_1, ...args_1) => __awaiter(void 0, [repoUrl_1, options_1, ...args_1], void 0, function* (repoUrl, options, deps = {
    isGitInstalled,
    execGitShallowClone,
}) {
    if (!(yield deps.isGitInstalled())) {
        throw new RepomixError('Git is not installed or not in the system PATH.');
    }
    const spinner = new Spinner('Cloning repository...');
    const tempDirPath = yield createTempDirectory();
    let result;
    try {
        spinner.start();
        // Clone the repository
        yield cloneRepository(formatGitUrl(repoUrl), tempDirPath, options.remoteBranch, {
            execGitShallowClone: deps.execGitShallowClone,
        });
        spinner.succeed('Repository cloned successfully!');
        logger.log('');
        // Run the default action on the cloned repository
        result = yield runDefaultAction(tempDirPath, tempDirPath, options);
        yield copyOutputToCurrentDirectory(tempDirPath, process.cwd(), result.config.output.filePath);
    }
    catch (error) {
        spinner.fail('Error during repository cloning. cleanup...');
        throw error;
    }
    finally {
        // Cleanup the temporary directory
        yield cleanupTempDirectory(tempDirPath);
    }
    return result;
});
export const formatGitUrl = (url) => {
    // If the URL is in the format owner/repo, convert it to a GitHub URL
    if (/^[a-zA-Z0-9_-]+\/[a-zA-Z0-9_-]+$/.test(url)) {
        logger.trace(`Formatting GitHub shorthand: ${url}`);
        return `https://github.com/${url}.git`;
    }
    // Add .git to HTTPS URLs if missing
    if (url.startsWith('https://') && !url.endsWith('.git')) {
        logger.trace(`Adding .git to HTTPS URL: ${url}`);
        return `${url}.git`;
    }
    return url;
};
export const createTempDirectory = () => __awaiter(void 0, void 0, void 0, function* () {
    const tempDir = yield fs.mkdtemp(path.join(os.tmpdir(), 'repomix-'));
    logger.trace(`Created temporary directory. (path: ${pc.dim(tempDir)})`);
    return tempDir;
});
export const cloneRepository = (url_1, directory_1, remoteBranch_1, ...args_1) => __awaiter(void 0, [url_1, directory_1, remoteBranch_1, ...args_1], void 0, function* (url, directory, remoteBranch, deps = {
    execGitShallowClone,
}) {
    logger.log(`Clone repository: ${url} to temporary directory. ${pc.dim(`path: ${directory}`)}`);
    logger.log('');
    try {
        yield deps.execGitShallowClone(url, directory, remoteBranch);
    }
    catch (error) {
        throw new RepomixError(`Failed to clone repository: ${error.message}`);
    }
});
export const cleanupTempDirectory = (directory) => __awaiter(void 0, void 0, void 0, function* () {
    logger.trace(`Cleaning up temporary directory: ${directory}`);
    yield fs.rm(directory, { recursive: true, force: true });
});
export const copyOutputToCurrentDirectory = (sourceDir, targetDir, outputFileName) => __awaiter(void 0, void 0, void 0, function* () {
    const sourcePath = path.join(sourceDir, outputFileName);
    const targetPath = path.join(targetDir, outputFileName);
    try {
        logger.trace(`Copying output file from: ${sourcePath} to: ${targetPath}`);
        yield fs.copyFile(sourcePath, targetPath);
    }
    catch (error) {
        throw new RepomixError(`Failed to copy output file: ${error.message}`);
    }
});
//# sourceMappingURL=remoteAction.js.map