import { readFileSync, readdirSync, existsSync } from "node:fs";
import { resolve } from "node:path";
import { readConfig, readAutoRespondConfig, writeAutoRespondConfig } from "../lib/credentials.js";
/**
 * Discover available public agents for the current account.
 * Returns slugs with display names for agent selection.
 */
function discoverPublicAgents(accountId) {
    const platformRoot = process.env.PLATFORM_ROOT;
    if (!platformRoot)
        return [];
    const agentsDir = resolve(platformRoot, "..", "data/accounts", accountId, "agents");
    if (!existsSync(agentsDir))
        return [];
    const agents = [];
    try {
        for (const entry of readdirSync(agentsDir, { withFileTypes: true })) {
            if (!entry.isDirectory() || entry.name === "admin")
                continue;
            const configPath = resolve(agentsDir, entry.name, "config.json");
            if (!existsSync(configPath))
                continue;
            try {
                const config = JSON.parse(readFileSync(configPath, "utf-8"));
                agents.push({
                    slug: entry.name,
                    displayName: config.displayName ?? entry.name,
                    status: config.status ?? "unknown",
                });
            }
            catch {
                // Skip agents with invalid config
            }
        }
    }
    catch {
        // Directory read failure — return empty
    }
    return agents;
}
export async function emailAutoRespondConfig(params) {
    // Verify email is configured
    const emailConfig = await readConfig(params.accountId);
    if (!emailConfig) {
        return {
            success: false,
            message: "Email is not configured. Run email-setup first before enabling auto-respond.",
        };
    }
    if (params.enabled) {
        // Enabling auto-respond — validate agent
        if (!params.agentSlug) {
            // Return available agents so the admin can select one
            const agents = discoverPublicAgents(params.accountId);
            if (agents.length === 0) {
                return {
                    success: false,
                    message: "No public agents found. Create a public agent first before enabling auto-respond.",
                };
            }
            return {
                success: false,
                message: "An agent must be assigned to handle email responses. Select a public agent from the list.",
                agents,
            };
        }
        // Validate the specified agent exists and is active
        const agents = discoverPublicAgents(params.accountId);
        const agent = agents.find((a) => a.slug === params.agentSlug);
        if (!agent) {
            return {
                success: false,
                message: `Agent "${params.agentSlug}" not found. Available agents: ${agents.map((a) => a.slug).join(", ")}`,
                agents,
            };
        }
        if (agent.status !== "active") {
            return {
                success: false,
                message: `Agent "${params.agentSlug}" is not active (status: ${agent.status}). Activate it first.`,
            };
        }
        // Validate poll interval
        const interval = params.pollIntervalMinutes ?? 5;
        if (interval < 1 || interval > 60) {
            return {
                success: false,
                message: "Poll interval must be between 1 and 60 minutes.",
            };
        }
        // Validate rate limits — cross-check against stored values when only one is provided
        const hourlyLimit = params.hourlyLimit;
        const dailyLimit = params.dailyLimit;
        if (hourlyLimit !== undefined && (hourlyLimit < 1 || hourlyLimit > 1000)) {
            return {
                success: false,
                message: "Hourly limit must be between 1 and 1000.",
            };
        }
        if (dailyLimit !== undefined && (dailyLimit < 1 || dailyLimit > 10000)) {
            return {
                success: false,
                message: "Daily limit must be between 1 and 10000.",
            };
        }
        // Cross-validate: resolve effective limits (provided or stored/default)
        if (hourlyLimit !== undefined || dailyLimit !== undefined) {
            const currentConfig = await readAutoRespondConfig(params.accountId);
            const effectiveHourly = hourlyLimit ?? (currentConfig?.autoRespondHourlyLimit ?? 20);
            const effectiveDaily = dailyLimit ?? (currentConfig?.autoRespondDailyLimit ?? 100);
            if (effectiveHourly > effectiveDaily) {
                return {
                    success: false,
                    message: `Hourly limit (${effectiveHourly}) cannot exceed daily limit (${effectiveDaily}).`,
                };
            }
        }
        // Enable auto-respond
        const configUpdate = {
            autoRespond: true,
            respondingAgentSlug: params.agentSlug,
            pollIntervalMinutes: interval,
            consecutiveFailures: 0,
        };
        if (hourlyLimit !== undefined)
            configUpdate.autoRespondHourlyLimit = hourlyLimit;
        if (dailyLimit !== undefined)
            configUpdate.autoRespondDailyLimit = dailyLimit;
        await writeAutoRespondConfig(params.accountId, configUpdate);
        const limitInfo = hourlyLimit !== undefined || dailyLimit !== undefined
            ? ` Rate limits: ${hourlyLimit ?? 20}/hour, ${dailyLimit ?? 100}/day.`
            : " Rate limits: 20/hour, 100/day (defaults).";
        return {
            success: true,
            message: `Auto-respond enabled. Agent "${agent.displayName}" (${params.agentSlug}) will respond to emails sent to ${emailConfig.agentAddress}. Polling every ${interval} minutes.${limitInfo}`,
        };
    }
    else {
        // Disabling auto-respond
        await writeAutoRespondConfig(params.accountId, {
            autoRespond: false,
            respondingAgentSlug: null,
            consecutiveFailures: 0,
        });
        return {
            success: true,
            message: "Auto-respond disabled. The agent will no longer respond to incoming emails.",
        };
    }
}
//# sourceMappingURL=email-auto-respond-config.js.map