"use strict";
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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var CliLoggerService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliLoggerService = void 0;
const common_1 = require("@nestjs/common");
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
/**
 * CLI Logger Service
 *
 * Manages operation logs for async CLI operations:
 * - Writes logs to ~/.flui/logs/<operation-id>.log
 * - Allows real-time log streaming
 * - Persists logs for later inspection
 */
let CliLoggerService = CliLoggerService_1 = class CliLoggerService {
    constructor() {
        this.logger = new common_1.Logger(CliLoggerService_1.name);
        this.fluiDir = path.join(os.homedir(), '.flui');
        this.logsDir = path.join(this.fluiDir, 'logs');
        this.ensureLogsDir();
    }
    /**
     * Ensure ~/.flui/logs directory exists
     */
    ensureLogsDir() {
        if (!fs.existsSync(this.logsDir)) {
            fs.mkdirSync(this.logsDir, { recursive: true, mode: 0o755 });
        }
    }
    /**
     * Get log file path for operation
     */
    getLogFilePath(operationId) {
        return path.join(this.logsDir, `${operationId}.log`);
    }
    /**
     * Write log message to operation log file
     */
    writeLog(operationId, message, level = 'INFO') {
        const logFilePath = this.getLogFilePath(operationId);
        const timestamp = new Date().toISOString();
        const logLine = `[${timestamp}] [${level}] ${message}\n`;
        try {
            fs.appendFileSync(logFilePath, logLine, { encoding: 'utf-8' });
        }
        catch (error) {
            this.logger.error(`Failed to write log to ${logFilePath}:`, error);
        }
    }
    /**
     * Read entire log file
     */
    readLog(operationId) {
        const logFilePath = this.getLogFilePath(operationId);
        if (!fs.existsSync(logFilePath)) {
            return '';
        }
        try {
            return fs.readFileSync(logFilePath, 'utf-8');
        }
        catch (error) {
            this.logger.error(`Failed to read log from ${logFilePath}:`, error);
            return '';
        }
    }
    /**
     * Read last N lines from log file
     */
    tailLog(operationId, lines = 100) {
        const content = this.readLog(operationId);
        if (!content)
            return '';
        const allLines = content.split('\n');
        const lastLines = allLines.slice(-lines);
        return lastLines.join('\n');
    }
    /**
     * Stream log file (for real-time monitoring)
     * Returns a readable stream
     */
    streamLog(operationId) {
        const logFilePath = this.getLogFilePath(operationId);
        if (!fs.existsSync(logFilePath)) {
            return null;
        }
        return fs.createReadStream(logFilePath, { encoding: 'utf-8' });
    }
    /**
     * Check if log file exists
     */
    hasLog(operationId) {
        const logFilePath = this.getLogFilePath(operationId);
        return fs.existsSync(logFilePath);
    }
    /**
     * Delete log file
     */
    deleteLog(operationId) {
        const logFilePath = this.getLogFilePath(operationId);
        if (fs.existsSync(logFilePath)) {
            fs.unlinkSync(logFilePath);
            this.logger.debug(`Deleted log file: ${logFilePath}`);
        }
    }
    /**
     * List all operation IDs with logs
     */
    listLogs() {
        if (!fs.existsSync(this.logsDir)) {
            return [];
        }
        const files = fs.readdirSync(this.logsDir);
        return files
            .filter((f) => f.endsWith('.log'))
            .map((f) => f.replace('.log', ''));
    }
    /**
     * Clean old logs (older than N days)
     */
    cleanOldLogs(daysOld = 30) {
        const files = fs.readdirSync(this.logsDir);
        const now = Date.now();
        const maxAge = daysOld * 24 * 60 * 60 * 1000;
        let deleted = 0;
        for (const file of files) {
            if (!file.endsWith('.log'))
                continue;
            const filePath = path.join(this.logsDir, file);
            const stats = fs.statSync(filePath);
            const age = now - stats.mtimeMs;
            if (age > maxAge) {
                fs.unlinkSync(filePath);
                deleted++;
            }
        }
        this.logger.log(`Cleaned ${deleted} old log files`);
        return deleted;
    }
};
exports.CliLoggerService = CliLoggerService;
exports.CliLoggerService = CliLoggerService = CliLoggerService_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [])
], CliLoggerService);
