import { jsx as _jsx } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { formatCost, formatGpuMemory, formatGpuUtilization, formatOllamaHost, formatSessionTokens, formatTokens, shortenMiddle } from "../format.js";
import { modeDescription, modePermissionLabel } from "../modes.js";
export function Sidebar(props) {
    const allRows = buildSidebarRows(props);
    const visibleCount = Math.max(1, props.height - 2);
    const maxOffset = Math.max(0, allRows.length - visibleCount);
    const offset = Math.max(0, Math.min(props.scrollOffset, maxOffset));
    const rows = allRows.slice(offset, offset + visibleCount);
    return (_jsx(Box, { width: 32, height: props.height, overflowY: "hidden", borderStyle: "round", borderColor: props.isActive ? "cyan" : "gray", flexDirection: "column", paddingX: 1, marginRight: 1, children: rows.map((row, index) => (_jsx(Text, { color: row.color, bold: row.bold, wrap: "truncate", children: row.text }, `${index}-${row.text}`))) }));
}
function buildSidebarRows(props) {
    const hostDeviceName = props.provider === "ollama" ? props.activeHost?.host.deviceName ?? formatOllamaHost(props.ollamaUrl) : `${props.provider} api`;
    const hostRoute = props.provider === "ollama" ? props.activeHost?.host.url ?? props.ollamaUrl : `${props.provider} cloud`;
    const hostNetwork = props.provider === "ollama" ? props.activeHost?.host.kind ?? "local" : "cloud";
    const hostVersion = props.activeHost?.host.version ?? "-";
    const hostModels = props.activeHost ? `${props.activeHost.models.length} available` : "-";
    const hostLoaded = props.activeHost?.runningModels.length ? props.activeHost.runningModels.map((model) => formatRunningModel(model)).join(", ") : "idle";
    const telemetryRows = compactTelemetryRows(props.telemetry, props.sessionTelemetry);
    const rows = [
        section("Session"),
        row("state", props.workState.replace(/_/g, " "), props.workState === "error" ? "red" : props.workState === "waiting_approval" ? "yellow" : "green"),
        row("mode", formatMode(props.agentMode), modeColor(props.agentMode)),
        row("session", shortenMiddle(props.sessionId, 18), "cyan"),
        row("agents", props.subagents ? "on" : "off", props.subagents ? "cyan" : "gray"),
        spacer(),
        section("Permissions"),
        muted(modeDescription(props.agentMode)),
        row("write", modePermissionLabel(props.agentMode, "write", props), permissionColor(props.agentMode, props.allowWrite)),
        row("shell", modePermissionLabel(props.agentMode, "shell", props), permissionColor(props.agentMode, props.allowShell)),
        spacer(),
        section("Model"),
        row("provider", props.provider, props.provider === "ollama" ? "green" : "cyan"),
        muted(shortenMiddle(props.model, 28)),
        spacer(),
        section(props.provider === "ollama" ? "Host" : "Route"),
        row("target", shortenMiddle(hostDeviceName, 19), "yellow"),
        row("network", hostNetwork, "green"),
        muted(shortenMiddle(hostRoute, 28)),
        ...(props.provider === "ollama" ? [muted(`ver ${hostVersion}  models ${hostModels}`), muted(`loaded ${shortenMiddle(hostLoaded, 21)}`)] : []),
        spacer(),
        section("Workspace"),
        muted(shortenMiddle(props.workspace, 28)),
        spacer(),
        section("Local machine"),
        muted(`cpu ${props.systemStats.cpuPercent}%  mem ${props.systemStats.memoryPercent}%/${props.systemStats.usedMemoryGb}G`),
        ...(props.provider === "ollama" && props.gpuStats ? [muted(`gpu ${formatGpuUtilization(props.gpuStats)}  vram ${formatGpuMemory(props.gpuStats)}`)] : []),
        muted(`draft prompt ${props.draftTokens} tok`),
        spacer(),
        section("Model usage"),
        ...telemetryRows,
        muted(formatCost(props.sessionTelemetry.estimatedCostUsd)),
        spacer(),
        section("Advisors")
    ];
    if (props.advisors.length === 0) {
        rows.push(muted("No advisor output yet."));
        return rows;
    }
    for (const advisor of props.advisors) {
        rows.push({
            text: advisor.role,
            color: "yellow"
        });
        rows.push(...summarizeAdvisorText(advisor.message));
        rows.push(spacer());
    }
    return rows;
}
function formatMode(agentMode) {
    return agentMode === "bypass" ? "build+bypass" : agentMode;
}
function modeColor(agentMode) {
    if (agentMode === "bypass") {
        return "red";
    }
    return agentMode === "build" ? "yellow" : "green";
}
function permissionColor(agentMode, enabled = false) {
    if (enabled || agentMode === "bypass") {
        return "red";
    }
    return agentMode === "build" ? "yellow" : "gray";
}
function section(text) {
    return {
        text,
        color: "cyan",
        bold: true
    };
}
function row(label, value, color) {
    return {
        text: `${label.padEnd(9)}${value}`,
        color
    };
}
function muted(text) {
    return {
        text,
        color: "gray"
    };
}
function spacer() {
    return muted("");
}
function wrapSidebarText(value) {
    return wrapText(value, 28).map(muted);
}
function summarizeAdvisorText(value) {
    const summary = value
        .replace(/\*\*/g, "")
        .split(/\r?\n/)
        .map((line) => line.replace(/^[-*]\s*/, "").trim())
        .filter(Boolean)
        .slice(0, 3)
        .join(" ");
    const rows = wrapText(summary || "Advisor brief available in transcript.", 28).slice(0, 4);
    return rows.map(muted);
}
function formatRunningModel(model) {
    const vram = model.sizeVramBytes ? ` ${Math.round((model.sizeVramBytes / 1024 ** 3) * 10) / 10}G vram` : "";
    return `${model.name}${vram}`;
}
function compactTelemetryRows(telemetry, sessionTelemetry) {
    const rows = [];
    if (telemetry) {
        rows.push(muted(formatTokens(telemetry)));
    }
    else {
        rows.push(muted("-"));
    }
    rows.push(muted(formatSessionTokens(sessionTelemetry)));
    return rows.flatMap((line) => wrapSidebarText(line.text).slice(0, 2));
}
function wrapText(value, width) {
    return value
        .split(/\r?\n/)
        .flatMap((line) => wrapLine(line, width));
}
function wrapLine(value, width) {
    const words = value.trimEnd().split(/\s+/).filter(Boolean);
    if (words.length === 0) {
        return [""];
    }
    const rows = [];
    let currentRow = "";
    for (const word of words) {
        const nextRow = currentRow ? `${currentRow} ${word}` : word;
        if (nextRow.length <= width) {
            currentRow = nextRow;
            continue;
        }
        if (currentRow) {
            rows.push(currentRow);
        }
        currentRow = word.length > width ? shortenMiddle(word, width) : word;
    }
    if (currentRow) {
        rows.push(currentRow);
    }
    return rows;
}
//# sourceMappingURL=Sidebar.js.map