import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { execSync } from 'child_process';
export const ATLAS_FOUNDATION_CAPABILITIES = [
    'code-intelligence',
    'ast-parsing',
    'semantic-search',
    'impact-analysis',
    'tool-relay',
];
function resolveAtlasConfigPath(home = os.homedir()) {
    return process.env.NEXUS_ATLAS_CONFIG_PATH?.trim() || path.join(home, '.goatlas', 'config.json');
}
function resolveAtlasBinaryPath() {
    const envPath = process.env.NEXUS_ATLAS_BINARY_PATH?.trim();
    if (envPath) {
        return envPath;
    }
    if (process.env.NEXUS_ATLAS_DISABLE_BINARY_LOOKUP === '1') {
        return null;
    }
    try {
        return execSync('command -v goatlas', {
            encoding: 'utf8',
            stdio: ['ignore', 'pipe', 'ignore'],
            timeout: 2000,
        }).trim() || null;
    }
    catch {
        return null;
    }
}
export function detectAtlasFoundation() {
    const checkedAt = Date.now();
    const configPath = resolveAtlasConfigPath();
    const binaryPath = resolveAtlasBinaryPath();
    const hasConfig = fs.existsSync(configPath);
    const detected = hasConfig || Boolean(binaryPath);
    const available = detected;
    const source = hasConfig ? 'config' : binaryPath ? 'binary' : 'none';
    const reason = detected
        ? 'Atlas foundation detected and available for later code-intelligence routing.'
        : 'Atlas foundation absent; fall back to built-in local-only capability selection until Atlas routing is enabled.';
    return {
        id: 'atlas',
        available,
        detected,
        mode: available ? 'ready' : 'fallback',
        source,
        configPath: hasConfig ? configPath : null,
        binaryPath,
        capabilities: available ? [...ATLAS_FOUNDATION_CAPABILITIES] : [],
        fallback: {
            active: !available,
            mode: 'local-only',
            reason,
            routingReady: false,
            preservesCandidateRanking: true,
        },
        reasons: [reason],
        checkedAt,
    };
}
/**
 * Scans standard paths in the user's home directory to dynamically
 * discover peer AI agent ecosystems like OpenClaw, Hermes, NanoClaw, PicoClaw, or Atlas.
 *
 * @returns Array of detected peer profiles
 */
export async function detectAllPeers() {
    const home = os.homedir();
    const peers = [];
    const seenPeerIds = new Set();
    const candidates = [
        { id: 'openclaw', relativeConfig: '.openclaw/openclaw.json' },
        { id: 'hermes', relativeConfig: '.hermes/config.yaml' },
        { id: 'hermes', relativeConfig: '.hermes/mcp.json' },
        { id: 'nanoclaw', relativeConfig: '.nanoclaw/mcp.json' },
        { id: 'picoclaw', relativeConfig: '.picoclaw/config.yaml' },
        { id: 'picoclaw', relativeConfig: '.picoclaw/mcp.json' },
        { id: 'opencode', relativeConfig: '.config/opencode/opencode.json' },
    ];
    for (const c of candidates) {
        const fullPath = path.join(home, c.relativeConfig);
        try {
            if (fs.existsSync(fullPath)) {
                if (seenPeerIds.has(c.id))
                    continue;
                seenPeerIds.add(c.id);
                const capabilities = ['skill-sharing', 'memory-sync', 'tool-relay', 'token-budgeting', 'workforce-hiring'];
                peers.push({
                    id: c.id,
                    configPath: fullPath,
                    detected: true,
                    capabilities,
                    lastSeen: Date.now()
                });
            }
        }
        catch (err) {
            // Silently ignore stat errors since these are external
        }
    }
    const atlas = detectAtlasFoundation();
    if (atlas.available) {
        peers.push({
            id: 'atlas',
            configPath: atlas.configPath ?? '',
            detected: true,
            capabilities: [...atlas.capabilities],
            lastSeen: atlas.checkedAt,
        });
    }
    return peers;
}
/**
 * Establishes a logical connection handshake with a discovered peer.
 *
 * @param peerId The identifier of the peer to connect to (e.g., 'atlas', 'openclaw')
 * @returns boolean indicating connection success
 */
export async function connectToPeer(peerId) {
    const peers = await detectAllPeers();
    const peer = peers.find(p => p.id === peerId);
    if (!peer) {
        return false;
    }
    // In future iterations, this maps to establishing actual IPC or local socket tunnels
    return true;
}
/**
 * Syncs the provided payload asynchronously over the established logical peer conduit.
 *
 * @param peer The peer profile to sync with
 * @param payload The data payload (memories, intents) to sync
 * @returns boolean indicating sync success
 */
export async function syncWithPeer(peer) {
    if (!peer.detected)
        return false;
    try {
        // Simulating the local routing mechanism across the host boundaries
        if (peer.id === 'atlas' && peer.capabilities.includes('code-intelligence')) {
            // AST routing optimization would occur here
            return true;
        }
        return true;
    }
    catch (err) {
        return false;
    }
}
