import { isServerRuntime } from '../utils/api.js';
/**
 * history.ts — List recent V3 agent runs with summaries.
 */
import chalk from 'chalk';
import { createRequire } from 'node:module';
import { createSpinner, CH } from '../utils/logger.js';
const require = createRequire(import.meta.url);
export class HistoryCommand {
    config;
    logger;
    constructor(config, logger) {
        this.config = config;
        this.logger = logger;
    }
    getHeaders() {
        const headers = { 'Content-Type': 'application/json' };
        const token = process.env.VIGTHORIA_TOKEN ||
            process.env.VIGTHORIA_AUTH_TOKEN ||
            this.config.get('authToken');
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
            headers['Cookie'] = `vigthoria-auth-token=${token}`;
        }
        const serviceKey = process.env.VIGTHORIA_V3_SERVICE_KEY;
        if (serviceKey)
            headers['X-Service-Key'] = serviceKey;
        return headers;
    }
    getBaseUrl() {
        const configuredApiUrl = String(this.config.get('apiUrl') || 'https://coder.vigthoria.io').replace(/\/$/, '');
        const allowLocal = isServerRuntime() && process.env.VIGTHORIA_ALLOW_LOCAL_V3_AGENT === '1';
        return (process.env.VIGTHORIA_V3_AGENT_URL ||
            process.env.V3_AGENT_URL ||
            (allowLocal ? 'http://127.0.0.1:8030' : null) ||
            configuredApiUrl);
    }
    resolveWorkspaceRoot(project) {
        // On Windows or non-absolute paths, send empty so the server uses its fallback root
        if (/^[a-zA-Z]:[\\/]/.test(project) || /^\\\\/.test(project))
            return '';
        if (typeof require !== 'undefined') {
            try {
                const path = require('path');
                if (!path.isAbsolute(project))
                    return '';
            }
            catch { }
        }
        return project;
    }
    async run(options) {
        const limit = options.limit || 20;
        const project = options.project || process.cwd();
        const workspace = this.resolveWorkspaceRoot(project);
        const spinner = createSpinner('Loading run history...').start();
        try {
            const baseUrl = this.getBaseUrl();
            const params = new URLSearchParams({
                limit: String(limit),
                workspace_root: workspace,
                local_workspace_path: project,
                project_path: project,
            });
            const resp = await fetch(`${baseUrl}/api/runs?${params}`, {
                headers: this.getHeaders(),
            });
            if (!resp.ok) {
                spinner.stop();
                if (resp.status === 404 || resp.status === 502 || resp.status === 503) {
                    this.logger.error(`V3 run-history route is not available on ${baseUrl}. Backend may not expose /api/runs.`);
                }
                else {
                    this.logger.error(`Failed to fetch runs: ${resp.status} ${resp.statusText}`);
                }
                return;
            }
            const data = (await resp.json());
            spinner.stop();
            if (options.json) {
                console.log(JSON.stringify(data, null, 2));
                return;
            }
            if (data.runs.length === 0) {
                this.logger.info(chalk.dim('No runs found.'));
                return;
            }
            console.log(chalk.bold(`\n${CH.success} Recent Runs (${data.count})\n`));
            for (const run of data.runs) {
                const tier = run.seal_score?.tier || 'unknown';
                const tierColor = tier === 'gold' ? chalk.yellow :
                    tier === 'silver' ? chalk.white :
                        tier === 'bronze' ? chalk.hex('#cd7f32') :
                            tier === 'failed' ? chalk.red :
                                chalk.dim;
                const score = run.seal_score?.overall != null ? `${run.seal_score.overall}` : '—';
                const status = run.failed > 0
                    ? chalk.red(`${run.completed}/${run.task_count} ✗`)
                    : chalk.green(`${run.completed}/${run.task_count} ✓`);
                console.log(`  ${chalk.cyan(run.run_id.substring(0, 16))}  ` +
                    `${chalk.dim(run.archived_at || '?')}  ` +
                    `${status}  ` +
                    `${tierColor(`[${tier} ${score}]`)}  ` +
                    `${chalk.white(run.request?.substring(0, 60) || '(no request)')}`);
            }
            console.log();
        }
        catch (err) {
            spinner.stop();
            this.logger.error(`History error: ${err.message}`);
        }
    }
}
