"use strict";
/**
 * Commit Storage
 * Handles filesystem operations for commits
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommitStorage = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class CommitStorage {
    bangstackDir;
    constructor(projectRoot) {
        const bangstackRoot = path.join(projectRoot, '.bangstack');
        this.bangstackDir = {
            root: bangstackRoot,
            config: path.join(bangstackRoot, 'config.yaml'),
            commits: path.join(bangstackRoot, 'commits'),
            commitIndex: path.join(bangstackRoot, 'commits', 'index.json'),
            state: path.join(bangstackRoot, 'state.json'),
            cache: path.join(bangstackRoot, 'cache'),
        };
    }
    /**
     * Initialize .bangstack directory structure
     */
    initialize() {
        // Create directories
        if (!fs.existsSync(this.bangstackDir.root)) {
            fs.mkdirSync(this.bangstackDir.root, { recursive: true });
        }
        if (!fs.existsSync(this.bangstackDir.commits)) {
            fs.mkdirSync(this.bangstackDir.commits, { recursive: true });
        }
        if (!fs.existsSync(this.bangstackDir.cache)) {
            fs.mkdirSync(this.bangstackDir.cache, { recursive: true });
        }
        // Create initial index if it doesn't exist
        if (!fs.existsSync(this.bangstackDir.commitIndex)) {
            const initialIndex = {
                head: null,
                commits: [],
            };
            this.saveIndex(initialIndex);
        }
    }
    /**
     * Check if .bangstack directory exists
     */
    exists() {
        return fs.existsSync(this.bangstackDir.root);
    }
    /**
     * Save a commit to disk
     */
    saveCommit(commit) {
        const commitPath = path.join(this.bangstackDir.commits, `${commit.hash}.json`);
        fs.writeFileSync(commitPath, JSON.stringify(commit, null, 2));
    }
    /**
     * Load a commit from disk
     */
    loadCommit(hash) {
        const commitPath = path.join(this.bangstackDir.commits, `${hash}.json`);
        if (!fs.existsSync(commitPath)) {
            return null;
        }
        const content = fs.readFileSync(commitPath, 'utf-8');
        return JSON.parse(content);
    }
    /**
     * Load commit index
     */
    loadIndex() {
        if (!fs.existsSync(this.bangstackDir.commitIndex)) {
            return { head: null, commits: [] };
        }
        const content = fs.readFileSync(this.bangstackDir.commitIndex, 'utf-8');
        return JSON.parse(content);
    }
    /**
     * Save commit index
     */
    saveIndex(index) {
        fs.writeFileSync(this.bangstackDir.commitIndex, JSON.stringify(index, null, 2));
    }
    /**
     * Update index with new commit
     */
    updateIndex(commit) {
        const index = this.loadIndex();
        // Add commit metadata to index
        const metadata = {
            hash: commit.hash,
            parent: commit.parent,
            timestamp: commit.timestamp,
            author: commit.author,
            message: commit.message,
        };
        index.commits.push(metadata);
        index.head = commit.hash;
        this.saveIndex(index);
    }
    /**
     * Get commit history (like git log)
     */
    getHistory(limit) {
        const index = this.loadIndex();
        if (limit) {
            return index.commits.slice(-limit).reverse();
        }
        return [...index.commits].reverse();
    }
    /**
     * Get current HEAD commit
     */
    getHead() {
        const index = this.loadIndex();
        if (!index.head) {
            return null;
        }
        return this.loadCommit(index.head);
    }
    /**
     * Get config file path
     */
    getConfigPath() {
        return this.bangstackDir.config;
    }
    /**
     * Check if config file exists
     */
    hasConfig() {
        return fs.existsSync(this.bangstackDir.config);
    }
    /**
     * Load config file
     */
    loadConfig() {
        if (!this.hasConfig()) {
            throw new Error('Config file not found: .bangstack/config.yaml');
        }
        return fs.readFileSync(this.bangstackDir.config, 'utf-8');
    }
    /**
     * Save config file
     */
    saveConfig(content) {
        fs.writeFileSync(this.bangstackDir.config, content);
    }
    /**
     * Get list of all commit hashes
     */
    listCommits() {
        const index = this.loadIndex();
        return index.commits.map(c => c.hash);
    }
    /**
     * Check if commit exists
     */
    hasCommit(hash) {
        const commitPath = path.join(this.bangstackDir.commits, `${hash}.json`);
        return fs.existsSync(commitPath);
    }
    /**
     * Delete a commit (use with caution!)
     */
    deleteCommit(hash) {
        const commitPath = path.join(this.bangstackDir.commits, `${hash}.json`);
        if (fs.existsSync(commitPath)) {
            fs.unlinkSync(commitPath);
        }
        // Update index
        const index = this.loadIndex();
        index.commits = index.commits.filter(c => c.hash !== hash);
        if (index.head === hash) {
            // Reset HEAD to previous commit
            const remainingCommits = index.commits;
            index.head = remainingCommits.length > 0
                ? remainingCommits[remainingCommits.length - 1].hash
                : null;
        }
        this.saveIndex(index);
    }
    /**
     * Get directory paths
     */
    getDirectories() {
        return this.bangstackDir;
    }
}
exports.CommitStorage = CommitStorage;
//# sourceMappingURL=commit-storage.js.map