"use strict";
/**
 * Log file management for Claude output
 * Generates and manages Markdown log files from Claude's responses
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getLogFilePath = getLogFilePath;
exports.createLog = createLog;
exports.appendToLog = appendToLog;
exports.readLog = readLog;
exports.listLogs = listLogs;
exports.cleanupOldLogs = cleanupOldLogs;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
const date_fns_1 = require("date-fns");
const env_1 = require("./env");
/**
 * Log directory configuration (with fallback support - Issue #76)
 */
const LOG_DIR = (0, env_1.getEnvByKey)('CM_LOG_DIR') || path_1.default.join(process.cwd(), 'data', 'logs');
/**
 * Get log directory for a CLI tool
 *
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 * @returns Log directory path
 */
function getCliToolLogDir(cliToolId = 'claude') {
    return path_1.default.join(LOG_DIR, cliToolId);
}
/**
 * Ensure log directory exists
 *
 * @param cliToolId - CLI tool ID (optional, defaults to 'claude')
 */
async function ensureLogDirectory(cliToolId = 'claude') {
    const logDir = getCliToolLogDir(cliToolId);
    try {
        await promises_1.default.access(logDir);
    }
    catch {
        await promises_1.default.mkdir(logDir, { recursive: true });
    }
}
/**
 * Get log file path for a worktree
 *
 * @param worktreeId - Worktree ID
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 * @returns Log file path
 *
 * @example
 * ```typescript
 * getLogFilePath('feature-foo', 'claude')
 * // => '/path/to/data/logs/claude/feature-foo-2025-01-20.md'
 * ```
 */
function getLogFilePath(worktreeId, cliToolId = 'claude') {
    const date = (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd');
    const filename = `${worktreeId}-${date}.md`;
    const logDir = getCliToolLogDir(cliToolId);
    return path_1.default.join(logDir, filename);
}
/**
 * Create a Markdown log file for a conversation
 *
 * @param worktreeId - Worktree ID
 * @param userMessage - User's message
 * @param claudeResponse - Claude's response
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 * @returns Path to the created log file
 *
 * @example
 * ```typescript
 * const logPath = await createLog(
 *   'feature-foo',
 *   'Explain this code',
 *   'This code implements...',
 *   'claude'
 * );
 * ```
 */
async function createLog(worktreeId, userMessage, claudeResponse, cliToolId = 'claude') {
    await ensureLogDirectory(cliToolId);
    const logPath = getLogFilePath(worktreeId, cliToolId);
    const timestamp = (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd HH:mm:ss');
    // Check if log file already exists
    let logContent = '';
    try {
        logContent = await promises_1.default.readFile(logPath, 'utf-8');
    }
    catch {
        // File doesn't exist, create header
        const toolName = cliToolId === 'claude' ? 'Claude Code' : cliToolId === 'codex' ? 'Codex CLI' : 'Gemini CLI';
        logContent = `# ${toolName} Conversation Log: ${worktreeId}\n\n`;
        logContent += `Created: ${timestamp}\n\n`;
        logContent += `---\n\n`;
    }
    // Append new conversation
    logContent += `## Conversation at ${timestamp}\n\n`;
    logContent += `### User\n\n`;
    logContent += `${userMessage}\n\n`;
    logContent += `### ${cliToolId === 'claude' ? 'Claude' : cliToolId === 'codex' ? 'Codex' : 'Gemini'}\n\n`;
    logContent += `${claudeResponse}\n\n`;
    logContent += `---\n\n`;
    await promises_1.default.writeFile(logPath, logContent, 'utf-8');
    return logPath;
}
/**
 * Append to existing log file
 *
 * @param worktreeId - Worktree ID
 * @param content - Content to append
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 *
 * @example
 * ```typescript
 * await appendToLog('feature-foo', 'Additional notes...', 'claude');
 * ```
 */
async function appendToLog(worktreeId, content, cliToolId = 'claude') {
    await ensureLogDirectory(cliToolId);
    const logPath = getLogFilePath(worktreeId, cliToolId);
    const timestamp = (0, date_fns_1.format)(new Date(), 'yyyy-MM-dd HH:mm:ss');
    let logContent = '';
    try {
        logContent = await promises_1.default.readFile(logPath, 'utf-8');
    }
    catch {
        // File doesn't exist, create header
        const toolName = cliToolId === 'claude' ? 'Claude Code' : cliToolId === 'codex' ? 'Codex CLI' : 'Gemini CLI';
        logContent = `# ${toolName} Conversation Log: ${worktreeId}\n\n`;
        logContent += `Created: ${timestamp}\n\n`;
        logContent += `---\n\n`;
    }
    logContent += `${content}\n\n`;
    await promises_1.default.writeFile(logPath, logContent, 'utf-8');
}
/**
 * Read log file content
 *
 * @param worktreeId - Worktree ID
 * @param cliToolId - CLI tool ID (claude, codex, gemini)
 * @returns Log file content, or null if file doesn't exist
 *
 * @example
 * ```typescript
 * const log = await readLog('feature-foo', 'claude');
 * if (log) {
 *   console.log(log);
 * }
 * ```
 */
async function readLog(worktreeId, cliToolId = 'claude') {
    const logPath = getLogFilePath(worktreeId, cliToolId);
    try {
        return await promises_1.default.readFile(logPath, 'utf-8');
    }
    catch {
        return null;
    }
}
/**
 * List all log files for a worktree
 *
 * @param worktreeId - Worktree ID
 * @param cliToolId - CLI tool ID (claude, codex, gemini), or 'all' for all tools
 * @returns Array of log file paths
 *
 * @example
 * ```typescript
 * const logs = await listLogs('feature-foo', 'claude');
 * // => ['/path/to/logs/claude/feature-foo-2025-01-20.md', '/path/to/logs/claude/feature-foo-2025-01-19.md']
 * ```
 */
async function listLogs(worktreeId, cliToolId = 'all') {
    const toolIds = cliToolId === 'all' ? ['claude', 'codex', 'gemini'] : [cliToolId];
    const allLogFiles = [];
    for (const toolId of toolIds) {
        await ensureLogDirectory(toolId);
        const logDir = getCliToolLogDir(toolId);
        try {
            const files = await promises_1.default.readdir(logDir);
            const logFiles = files
                .filter((file) => file.startsWith(`${worktreeId}-`) && file.endsWith('.md'))
                .map((file) => path_1.default.join(logDir, file));
            allLogFiles.push(...logFiles);
        }
        catch {
            // Directory doesn't exist or is not accessible, skip
        }
    }
    return allLogFiles.sort().reverse(); // Most recent first
}
/**
 * Delete old log files (older than specified days)
 *
 * @param days - Number of days to keep
 *
 * @example
 * ```typescript
 * // Delete logs older than 30 days
 * await cleanupOldLogs(30);
 * ```
 */
async function cleanupOldLogs(days = 30) {
    const toolIds = ['claude', 'codex', 'gemini'];
    let totalDeletedCount = 0;
    const now = new Date();
    const cutoffDate = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);
    for (const toolId of toolIds) {
        await ensureLogDirectory(toolId);
        const logDir = getCliToolLogDir(toolId);
        try {
            const files = await promises_1.default.readdir(logDir);
            for (const file of files) {
                if (!file.endsWith('.md'))
                    continue;
                const filePath = path_1.default.join(logDir, file);
                const stats = await promises_1.default.stat(filePath);
                if (stats.mtime < cutoffDate) {
                    await promises_1.default.unlink(filePath);
                    totalDeletedCount++;
                }
            }
        }
        catch (error) {
            console.error(`Error cleaning up old logs for ${toolId}:`, error);
        }
    }
    return totalDeletedCount;
}
