"use strict";
// src/cli/GitignoreManager.ts
// Opt-in .gitignore management for OpenLife-installed files.
//
// The host installer (HostInstaller.ts) deliberately does NOT touch .gitignore —
// some teams want to commit the openlife config, others want to ignore it.
// This module provides a dedicated verb (`openlife gitignore`) for that choice.
//
// Paths to ignore are sourced from install-state.json (repoPaths) when available,
// falling back to the known default set. This keeps the gitignore in sync with
// what was actually installed rather than a hardcoded list.
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.GitignoreManager = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const BLOCK_START = '# >>> openlife (managed) >>>';
const BLOCK_END = '# <<< openlife (managed) <<<';
const DEFAULT_REPO_PATHS = [
    '.openlife/',
    '.claude/commands/openlife/',
    '.claude/agents/openlife-*',
    'OPENLIFE_PROJECT.md',
];
class GitignoreManager {
    root;
    constructor(root = process.cwd()) {
        this.root = root;
    }
    gitignorePath() {
        return path.join(this.root, '.gitignore');
    }
    repoPaths() {
        const statePath = path.join(this.root, '.openlife', 'install-state.json');
        if (fs.existsSync(statePath)) {
            try {
                const state = JSON.parse(fs.readFileSync(statePath, 'utf-8'));
                if (Array.isArray(state.repoPaths) && state.repoPaths.length > 0) {
                    return state.repoPaths;
                }
            }
            catch {
                // malformed state — fall through to defaults
            }
        }
        return DEFAULT_REPO_PATHS;
    }
    status() {
        const gitignorePath = this.gitignorePath();
        const patterns = this.repoPaths();
        if (!fs.existsSync(gitignorePath)) {
            return {
                gitignorePath,
                blockPresent: false,
                entries: patterns.map((p) => ({ pattern: p, ignored: false })),
            };
        }
        const content = fs.readFileSync(gitignorePath, 'utf-8');
        const lines = content.split('\n');
        const blockPresent = lines.some((l) => l.trim() === BLOCK_START);
        const entries = patterns.map((p) => ({
            pattern: p,
            ignored: lines.some((l) => l.trim() === p.trim()),
        }));
        return { gitignorePath, blockPresent, entries };
    }
    apply() {
        const gitignorePath = this.gitignorePath();
        const patterns = this.repoPaths();
        let existing = '';
        if (fs.existsSync(gitignorePath)) {
            existing = fs.readFileSync(gitignorePath, 'utf-8');
        }
        if (existing.includes(BLOCK_START)) {
            return { added: [], alreadyPresent: true };
        }
        const block = [
            '',
            BLOCK_START,
            ...patterns,
            BLOCK_END,
            '',
        ].join('\n');
        fs.writeFileSync(gitignorePath, existing.trimEnd() + block, 'utf-8');
        return { added: patterns, alreadyPresent: false };
    }
    remove() {
        const gitignorePath = this.gitignorePath();
        if (!fs.existsSync(gitignorePath))
            return { removed: false };
        const content = fs.readFileSync(gitignorePath, 'utf-8');
        const lines = content.split('\n');
        let inBlock = false;
        const kept = [];
        for (const line of lines) {
            if (line.trim() === BLOCK_START) {
                inBlock = true;
                continue;
            }
            if (line.trim() === BLOCK_END) {
                inBlock = false;
                continue;
            }
            if (!inBlock)
                kept.push(line);
        }
        if (kept.length === lines.length)
            return { removed: false };
        fs.writeFileSync(gitignorePath, kept.join('\n'), 'utf-8');
        return { removed: true };
    }
}
exports.GitignoreManager = GitignoreManager;
