#! /usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const open_1 = __importDefault(require("open"));
const server_1 = require("./server");
const prompts_1 = __importDefault(require("prompts"));
const utils_1 = require("./utils");
const runConclusionUtils_1 = require("./runConclusion/runConclusionUtils");
const updateHistoryFromRootCauseResultsOnly_1 = require("./updateHistoryFromRootCauseResultsOnly");
const persist_1 = require("./persist");
const serverPort = 9876;
commander_1.program.version(getVersion());
async function show(testId, { failed: showOnlyFailed = false } = {}) {
    const resultsDirPath = utils_1.constructResultDir(process.cwd());
    const history = await runConclusionUtils_1.readRunsHistory(resultsDirPath);
    let conclusion = null;
    let runId = '';
    if (history.length === 0) {
        try {
            conclusion = await updateHistoryFromRootCauseResultsOnly_1.readHistoryFallback();
            runId = conclusion.runId;
        }
        catch (err) {
            if (history.length === 0) {
                console.log('No Root Cause runs found');
                console.log('Make sure you have the .root-cause directory in your working directory');
                return;
            }
        }
    }
    if (!conclusion) {
        const mostRecentHistory = history[0];
        runId = mostRecentHistory.runId;
        conclusion = await runConclusionUtils_1.readRunConclusion(resultsDirPath, runId);
    }
    if (testId) {
        if (conclusion.tests.findIndex((t) => t.id === testId) === -1) {
            console.error(`Test with id ${testId} is missing`);
            process.exit(1);
            return;
        }
        const url = await server_1.openServer(serverPort, utils_1.constructTestResultDir(process.cwd(), runId, testId));
        open_1.default(url);
        console.log('Press any key to exit');
        if (process.stdin.isTTY) {
            process.stdin.setRawMode(true);
        }
        process.stdin.resume();
        process.stdin.on('data', process.exit.bind(process, 0));
    }
    else {
        const selectedTest = await prompts_1.default({
            type: 'select',
            name: 'test',
            message: `Please select which test run to show (runId ${conclusion.runId}):`,
            choices: conclusion.tests
                .filter((t) => (showOnlyFailed ? !t.success : true))
                .map((p) => ({ title: `${p.name} (${p.id})`, value: p.id })),
        });
        if (selectedTest.test !== undefined) {
            show(selectedTest.test);
        }
        else {
        }
    }
}
async function list({ simple = false, failed: showOnlyFailed = false, } = {}) {
    const resultsDirPath = utils_1.constructResultDir(process.cwd());
    const history = await runConclusionUtils_1.readRunsHistory(resultsDirPath);
    if (history.length === 0) {
        console.log('No Root Cause runs found');
        return;
    }
    let conclusion = null;
    let runId = '';
    if (history.length === 0) {
        try {
            conclusion = await updateHistoryFromRootCauseResultsOnly_1.readHistoryFallback();
            runId = conclusion.runId;
        }
        catch (err) {
            if (history.length === 0) {
                console.log('No Root Cause runs found');
                console.log('Make sure you have the .root-cause directory in your working directory');
                return;
            }
        }
    }
    if (!conclusion) {
        const mostRecentHistory = history[0];
        runId = mostRecentHistory.runId;
        conclusion = await runConclusionUtils_1.readRunConclusion(resultsDirPath, runId);
    }
    if (simple) {
        for (const test of conclusion.tests) {
            console.log(test.id);
        }
        return;
    }
    console.log(`Run id: ${conclusion.runId}`);
    console.log(`Run time: ${new Date(conclusion.timestamp).toISOString()}`);
    const tableData = conclusion.tests
        .filter((t) => (showOnlyFailed ? !t.success : true))
        .map(({ id, name, success }) => ({
        id,
        name,
        success,
    }));
    console.table(tableData);
}
function version() {
    console.log(getVersion());
}
function getVersion() {
    const version = require('../package.json').version;
    return version;
}
function login() {
    const loginUrl = 'https://app.testim.io/#/signin?fromRootCause=true';
    open_1.default(loginUrl);
}
commander_1.program
    .command('show [testId]')
    .description('shows test result ui')
    .option('-f, --failed', 'show only failed tests')
    .action(show);
commander_1.program
    .command('persist [runId]')
    .description('persists the given cloud result to the Testim Cloud')
    .option('--result-label [resultLabel]', 'result label to tag at Testim Cloud with')
    .option('--project')
    .option('--token')
    .action(persist_1.persist);
commander_1.program
    .command('list')
    .alias('ls')
    .option('-s, --simple', 'print simple output, as unformatted as possible')
    .option('-f, --failed', 'show only failed tests')
    .description('list all Root Cause tests in the last run')
    .action(list);
commander_1.program.option('-v').description('output the version number').action(version);
commander_1.program.command('login').description('logs in to testim').action(login);
commander_1.program.parse(process.argv);
