/**
 * Enterprise Managed Policies
 *
 * Reads organization-level policies from system paths to enforce
 * tool restrictions, command restrictions, cost limits, and model allowlists.
 *
 * Policy files:
 * - /etc/codebuddy/managed-settings.json (Linux system-wide)
 * - ~/.codebuddy/managed-settings.json (fallback for testing)
 */
import fs from 'fs';
import path from 'path';
import os from 'os';
import { logger } from '../utils/logger.js';
// ============================================================================
// Constants
// ============================================================================
const SYSTEM_MANAGED_PATH = '/etc/codebuddy/managed-settings.json';
const USER_MANAGED_PATH = path.join(os.homedir(), '.codebuddy', 'managed-settings.json');
const DEFAULT_POLICIES = {
    allowManagedPermissionRulesOnly: false,
    allowManagedHooksOnly: false,
    disallowedTools: [],
    disallowedCommands: [],
};
// ============================================================================
// ManagedPoliciesManager
// ============================================================================
export class ManagedPoliciesManager {
    policies = { ...DEFAULT_POLICIES };
    managed = false;
    systemPath;
    userPath;
    constructor(systemPath, userPath) {
        this.systemPath = systemPath ?? SYSTEM_MANAGED_PATH;
        this.userPath = userPath ?? USER_MANAGED_PATH;
        this.loadPolicies();
    }
    /**
     * Load policies from managed settings files.
     * System path takes priority over user path.
     */
    loadPolicies() {
        // Try system path first
        const loaded = this.tryLoadFrom(this.systemPath) || this.tryLoadFrom(this.userPath);
        if (!loaded) {
            this.policies = { ...DEFAULT_POLICIES };
            this.managed = false;
            logger.debug('No managed policies found', { source: 'ManagedPoliciesManager' });
        }
    }
    tryLoadFrom(filePath) {
        try {
            if (!fs.existsSync(filePath)) {
                return false;
            }
            const content = fs.readFileSync(filePath, 'utf-8');
            const parsed = JSON.parse(content);
            this.policies = {
                allowManagedPermissionRulesOnly: parsed.allowManagedPermissionRulesOnly ?? false,
                allowManagedHooksOnly: parsed.allowManagedHooksOnly ?? false,
                disallowedTools: Array.isArray(parsed.disallowedTools) ? parsed.disallowedTools : [],
                disallowedCommands: Array.isArray(parsed.disallowedCommands) ? parsed.disallowedCommands : [],
                maxSessionCost: typeof parsed.maxSessionCost === 'number' ? parsed.maxSessionCost : undefined,
                allowedModels: Array.isArray(parsed.allowedModels) ? parsed.allowedModels : undefined,
            };
            this.managed = true;
            logger.info(`Loaded managed policies from ${filePath}`, { source: 'ManagedPoliciesManager' });
            return true;
        }
        catch (error) {
            logger.warn(`Failed to load managed policies from ${filePath}: ${error}`, { source: 'ManagedPoliciesManager' });
            return false;
        }
    }
    /**
     * Check if a tool is allowed by managed policies
     */
    isToolAllowed(toolName) {
        return !this.policies.disallowedTools.includes(toolName);
    }
    /**
     * Check if a command is allowed by managed policies.
     * Checks if any disallowed command pattern appears in the command string.
     */
    isCommandAllowed(command) {
        for (const disallowed of this.policies.disallowedCommands) {
            if (command.includes(disallowed)) {
                return false;
            }
        }
        return true;
    }
    /**
     * Get the current policies
     */
    getPolicies() {
        return { ...this.policies };
    }
    /**
     * Check if managed policies are active (file exists and was loaded)
     */
    isManaged() {
        return this.managed;
    }
}
// ============================================================================
// Singleton
// ============================================================================
let instance = null;
export function getManagedPoliciesManager(systemPath, userPath) {
    if (!instance || systemPath || userPath) {
        instance = new ManagedPoliciesManager(systemPath, userPath);
    }
    return instance;
}
export function resetManagedPolicies() {
    instance = null;
}
//# sourceMappingURL=managed-policies.js.map