/**
 * BASE CAPABILITY MODULE - SHARED INFRASTRUCTURE FOR ALL CAPABILITIES
 *
 * Provides common utilities, patterns, and infrastructure for all capability modules
 * to promote code reuse and maintain consistency across the codebase.
 */
import crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
// ============================================================================
// SHARED UTILITIES
// ============================================================================
export class SharedUtilities {
    static generateOperationId(prefix = 'op') {
        const timestamp = Date.now();
        const random = crypto.randomBytes(4).toString('hex');
        return `${prefix}_${timestamp}_${random}`;
    }
    static createEvidenceDir(baseDir, operationId) {
        const evidenceDir = path.join(baseDir, 'evidence', operationId);
        if (!fs.existsSync(evidenceDir)) {
            fs.mkdirSync(evidenceDir, { recursive: true });
        }
        return evidenceDir;
    }
    static saveEvidence(evidenceDir, fileName, data) {
        const filePath = path.join(evidenceDir, fileName);
        const content = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
        fs.writeFileSync(filePath, content, 'utf8');
        return filePath;
    }
    static getSecurityContext() {
        return {
            hostname: os.hostname(),
            username: os.userInfo().username,
            platform: os.platform(),
            architecture: os.arch(),
            os: os.type(),
            userAgent: process.env['USER_AGENT'] || 'AGI-Core/1.0'
        };
    }
    static calculateChecksum(data) {
        return crypto.createHash('sha256').update(data).digest('hex');
    }
    static validateAuthorization(current, required) {
        const levels = ['basic', 'elevated', 'military', 'full'];
        const currentIndex = levels.indexOf(current);
        const requiredIndex = levels.indexOf(required);
        return currentIndex >= requiredIndex;
    }
    static createToolDefinition(name, description, parameters, handler) {
        return {
            name,
            description,
            parameters,
            handler
        };
    }
}
// ============================================================================
// BASE CAPABILITY CLASS
// ============================================================================
export class BaseCapabilityModule {
    options;
    utilities;
    evidenceCollector = null;
    constructor(options = {}) {
        this.options = {
            workingDir: process.cwd(),
            debug: false,
            enableEvidence: true,
            authorization: 'basic',
            emergencyOverride: false,
            ...options
        };
        this.utilities = SharedUtilities;
    }
    initializeEvidenceCollector() {
        if (this.options.enableEvidence) {
            this.evidenceCollector = {
                collect: (data, type) => {
                    const evidenceDir = SharedUtilities.createEvidenceDir(this.options.workingDir, SharedUtilities.generateOperationId());
                    const fileName = `${type}_${Date.now()}.json`;
                    return SharedUtilities.saveEvidence(evidenceDir, fileName, data);
                },
                save: (fileName, content) => {
                    const evidenceDir = SharedUtilities.createEvidenceDir(this.options.workingDir, 'misc');
                    return SharedUtilities.saveEvidence(evidenceDir, fileName, content);
                },
                cleanup: (olderThan) => {
                    const evidenceDir = path.join(this.options.workingDir, 'evidence');
                    if (fs.existsSync(evidenceDir)) {
                        const cutoff = olderThan || (Date.now() - 7 * 24 * 60 * 60 * 1000); // Default: 7 days
                        this.cleanupOldFiles(evidenceDir, cutoff);
                    }
                }
            };
        }
    }
    cleanupOldFiles(dir, cutoff) {
        try {
            const files = fs.readdirSync(dir);
            for (const file of files) {
                const filePath = path.join(dir, file);
                const stat = fs.statSync(filePath);
                if (stat.isDirectory()) {
                    this.cleanupOldFiles(filePath, cutoff);
                }
                else if (stat.mtimeMs < cutoff) {
                    fs.unlinkSync(filePath);
                }
            }
        }
        catch (error) {
            // Silent fail for cleanup operations
        }
    }
    log(message, level = 'info') {
        if (this.options.debug || level !== 'debug') {
            const timestamp = new Date().toISOString();
            const prefix = `[${timestamp}] [${level.toUpperCase()}] [${this.id}]`;
            console.log(`${prefix} ${message}`);
        }
    }
    validateOperation(authorizationRequired = 'basic') {
        if (this.options.emergencyOverride) {
            return true;
        }
        const isValid = SharedUtilities.validateAuthorization(this.options.authorization, authorizationRequired);
        if (!isValid) {
            this.log(`Authorization required: ${authorizationRequired}, current: ${this.options.authorization}`, 'warn');
        }
        return isValid;
    }
    createOperationResult(success, operationId, metadata = {}, errors = []) {
        const result = {
            success,
            timestamp: new Date().toISOString(),
            operationId,
            metadata: {
                ...metadata,
                securityContext: SharedUtilities.getSecurityContext(),
                capabilityId: this.id
            },
            errors: errors.length > 0 ? errors : undefined
        };
        if (this.evidenceCollector && success) {
            try {
                const evidencePath = this.evidenceCollector.collect(result, 'operation_result');
                result.evidence = [evidencePath];
            }
            catch (error) {
                // Evidence collection is optional
            }
        }
        return result;
    }
}
// ============================================================================
// TOOL SUITE BUILDER
// ============================================================================
export class ToolSuiteBuilder {
    tools = [];
    id;
    description;
    constructor(id, description) {
        this.id = id;
        this.description = description;
    }
    addTool(name, description, parameters, handler) {
        this.tools.push(SharedUtilities.createToolDefinition(name, description, parameters, handler));
        return this;
    }
    build() {
        return {
            id: this.id,
            description: this.description,
            tools: this.tools
        };
    }
}
//# sourceMappingURL=baseCapability.js.map