"use strict";
/**
 * Baseline Manager
 * Handles loading, saving, and clearing baseline files
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaselineManager = void 0;
const fs_1 = require("fs");
const path_1 = require("path");
const child_process_1 = require("child_process");
const types_1 = require("./types");
const hash_1 = require("../suppression/hash");
/**
 * Get current git commit SHA (short form)
 */
function getGitCommit(projectPath) {
    try {
        const result = (0, child_process_1.execFileSync)('git', ['rev-parse', '--short', 'HEAD'], {
            cwd: projectPath,
            stdio: ['ignore', 'pipe', 'ignore'],
        });
        return result.toString().trim();
    }
    catch {
        return undefined;
    }
}
/**
 * Get current git branch name
 */
function getGitBranch(projectPath) {
    try {
        const result = (0, child_process_1.execFileSync)('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
            cwd: projectPath,
            stdio: ['ignore', 'pipe', 'ignore'],
        });
        return result.toString().trim();
    }
    catch {
        return undefined;
    }
}
/**
 * Convert a Vulnerability to a BaselineFinding
 */
function toBaselineFinding(vuln) {
    return {
        hash: (0, hash_1.computeFindingHash)(vuln),
        filePath: vuln.filePath,
        lineNumber: vuln.lineNumber,
        category: vuln.category,
        severity: vuln.severity,
        title: vuln.title,
    };
}
/**
 * Manages baseline files for diff mode
 */
class BaselineManager {
    constructor(options) {
        // Support both old string arg and new options object
        if (typeof options === 'string') {
            this.projectPath = options;
        }
        else {
            this.projectPath = options.projectPath;
        }
        this.baselinePath = (0, path_1.join)(this.projectPath, types_1.BASELINE_FILE_PATH);
    }
    /**
     * Get the full path to the baseline file
     */
    getBaselinePath() {
        return this.baselinePath;
    }
    /**
     * Load baseline from .oculum/baseline.json
     */
    loadBaseline() {
        if (!(0, fs_1.existsSync)(this.baselinePath)) {
            return { found: false };
        }
        try {
            const content = (0, fs_1.readFileSync)(this.baselinePath, 'utf-8');
            const baseline = JSON.parse(content);
            // Basic validation
            if (baseline.version !== 1) {
                return {
                    found: false,
                    error: `Unsupported baseline version: ${baseline.version}. Expected version 1.`,
                };
            }
            if (!Array.isArray(baseline.findings)) {
                return {
                    found: false,
                    error: 'Invalid baseline: missing findings array',
                };
            }
            return { found: true, baseline };
        }
        catch (err) {
            return {
                found: false,
                error: `Failed to parse baseline: ${err instanceof Error ? err.message : 'Unknown error'}`,
            };
        }
    }
    /**
     * Save current scan result as baseline
     */
    saveBaseline(scanResult, options) {
        try {
            // Ensure .oculum directory exists
            const oculumDir = (0, path_1.join)(this.projectPath, types_1.OCULUM_DIR);
            if (!(0, fs_1.existsSync)(oculumDir)) {
                (0, fs_1.mkdirSync)(oculumDir, { recursive: true });
            }
            // Get git info if not provided
            const commit = options?.commit ?? getGitCommit(this.projectPath);
            const branch = options?.branch ?? getGitBranch(this.projectPath);
            // Convert vulnerabilities to baseline findings
            const findings = scanResult.vulnerabilities.map(toBaselineFinding);
            // Build baseline data
            const baseline = {
                version: 1,
                createdAt: new Date().toISOString(),
                commit,
                branch,
                scanDepth: options?.scanDepth,
                findings,
                stats: {
                    total: findings.length,
                    critical: scanResult.severityCounts.critical,
                    high: scanResult.severityCounts.high,
                    medium: scanResult.severityCounts.medium,
                    low: scanResult.severityCounts.low,
                    info: scanResult.severityCounts.info,
                },
            };
            // Write to file
            (0, fs_1.writeFileSync)(this.baselinePath, JSON.stringify(baseline, null, 2));
            return { success: true, path: this.baselinePath };
        }
        catch (err) {
            return {
                success: false,
                path: this.baselinePath,
                error: `Failed to save baseline: ${err instanceof Error ? err.message : 'Unknown error'}`,
            };
        }
    }
    /**
     * Clear (delete) the baseline file
     */
    clearBaseline() {
        const existed = (0, fs_1.existsSync)(this.baselinePath);
        if (!existed) {
            return { success: true, existed: false };
        }
        try {
            (0, fs_1.unlinkSync)(this.baselinePath);
            return { success: true, existed: true };
        }
        catch (err) {
            return {
                success: false,
                existed: true,
                error: `Failed to clear baseline: ${err instanceof Error ? err.message : 'Unknown error'}`,
            };
        }
    }
    /**
     * Check if a baseline exists
     */
    hasBaseline() {
        return (0, fs_1.existsSync)(this.baselinePath);
    }
}
exports.BaselineManager = BaselineManager;
//# sourceMappingURL=manager.js.map