import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Box, Text } from "ink";
import { useTerminalSize } from "../hooks/useTerminalSize.js";
import { AgentProgressLine, agentProgressLineModel } from "./AgentProgressLine.js";
import { Pane } from "./design/Pane.js";
import { SelectList } from "./design/SelectList.js";
import { StatusBadge } from "./design/StatusBadge.js";
import { Tabs } from "./design/Tabs.js";
import { truncateCells } from "./design/textLayout.js";
export function AgentPanel(props) {
    const { columns } = useTerminalSize();
    const width = Math.max(58, Math.min(112, columns - 4));
    const groupOptions = agentPanelGroupOptions(props.model);
    const selectedGroup = groupOptions.find((option) => option.selected)?.id;
    const rowOptions = agentPanelRowOptions(props.model, selectedGroup);
    const progress = props.model.progress ?? [];
    return (_jsx(Box, { flexDirection: "column", marginBottom: 1, children: _jsxs(Pane, { width: width, title: "agents", tone: props.model.rows.length > 0 ? "brand" : "muted", paddingX: 1, children: [_jsxs(Box, { flexDirection: "row", justifyContent: "space-between", children: [_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { bold: true, color: "cyan", children: props.model.title }), _jsx(Text, { color: "gray", children: truncateCells(props.model.subtitle, Math.max(24, width - 20)) })] }), _jsxs(Box, { flexDirection: "column", alignItems: "flex-end", children: [_jsx(StatusBadge, { label: `${props.model.rows.length} rows`, tone: props.model.rows.length > 0 ? "brand" : "muted" }), _jsx(Text, { color: "gray", children: agentPanelStatusLine(props.model) })] })] }), _jsx(Box, { marginTop: 1, children: _jsx(Tabs, { selectedId: "agents", title: "view", tabs: agentPanelTabs(props.model), width: width }) }), groupOptions.length > 0 ? (_jsxs(_Fragment, { children: [_jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "gray", children: "sources / states" }) }), _jsx(SelectList, { options: groupOptions, selectedIndex: 0, visibleCount: 5, width: width })] })) : null, _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "gray", children: selectedGroup ? `agents in ${selectedGroup}` : "agents" }) }), rowOptions.length > 0 ? (_jsx(SelectList, { options: rowOptions, selectedIndex: 0, visibleCount: 6, width: width })) : (_jsx(Text, { color: "gray", children: "No agents discovered" })), progress.length > 0 ? (_jsx(AgentProgressBlock, { progress: progress, width: width })) : null, props.model.preview && props.model.preview.length > 0 ? (_jsx(AgentPreviewBlock, { lines: props.model.preview, width: width })) : null, _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: "gray", children: "commands" }) }), _jsx(SelectList, { options: agentPanelCommandOptions(props.model), selectedIndex: 0, visibleCount: 5, width: width }), _jsx(Text, { color: "gray", children: truncateCells(props.model.footer, Math.max(24, width - 4)) })] }) }));
}
export function agentListPanelModel(agents) {
    return {
        title: "Agents",
        subtitle: `${agents.length} discovered agent${agents.length === 1 ? "" : "s"}`,
        rows: agents.map((agent) => ({
            key: `${agent.scope}/${agent.name}`,
            name: `${agent.scope}/${agent.name}`,
            status: agent.scope,
            tone: toneForScope(agent.scope),
            detail: agent.description || "(no description)",
            note: agent.path,
        })),
        footer: "/agents show <name> | /agents start <name> <task> | /agents create-smart <name> <goal>",
    };
}
export function agentDetailPanelModel(agent) {
    return {
        title: `Agent: ${agent.name}`,
        subtitle: `${agent.scope} / ${agent.path}`,
        rows: [{
                key: `${agent.scope}/${agent.name}`,
                name: `${agent.scope}/${agent.name}`,
                status: agent.model || "inherit",
                tone: toneForScope(agent.scope),
                detail: agent.description || agent.frontmatter.whenToUse || "(no description)",
                note: [
                    agent.tools?.length ? `tools=${agent.tools.join(",")}` : "tools=inherited",
                    agent.frontmatter.disallowedTools?.length ? `deny=${agent.frontmatter.disallowedTools.join(",")}` : "",
                    agent.skills?.length ? `skills=${agent.skills.join(",")}` : "",
                    agent.frontmatter.maxTurns ? `max-turns=${agent.frontmatter.maxTurns}` : "",
                ].filter(Boolean).join(" "),
            }],
        preview: previewLines(agent.prompt),
        footer: `/agents run ${agent.name} <task> | /agents validate ${agent.name}`,
    };
}
export function agentValidationPanelModel(results) {
    return {
        title: "Agent validation",
        subtitle: `${results.length} validation result${results.length === 1 ? "" : "s"}`,
        rows: results.map((result) => ({
            key: result.name,
            name: result.name,
            status: result.ok ? "ok" : "failed",
            tone: result.ok ? "success" : "error",
            detail: result.path || "(missing)",
            note: [
                ...result.errors.map((error) => `error: ${error}`),
                ...result.warnings.map((warning) => `warning: ${warning}`),
            ].join("; "),
        })),
        footer: "/agents list | /agents show <name>",
    };
}
export function agentWizardPanelModel(plan) {
    return {
        title: "Agent wizard plan",
        subtitle: plan.description,
        rows: [{
                key: plan.name,
                name: plan.name,
                status: `${plan.maxTurns} turns`,
                tone: "brand",
                detail: `tools=${plan.tools.join(",")}`,
                note: [
                    plan.disallowedTools.length ? `deny=${plan.disallowedTools.join(",")}` : "deny=none",
                    `color=${plan.color}`,
                ].join(" "),
            }],
        preview: [...plan.rationale, "", ...previewLines(plan.prompt)],
        footer: `/agents create-smart ${plan.name} <goal>`,
    };
}
export function agentRunsPanelModel(runs) {
    return {
        title: "Agent runs",
        subtitle: `${runs.length} recent run${runs.length === 1 ? "" : "s"}`,
        rows: runs.map(({ run, tasks }, index) => ({
            key: run.id,
            name: runListLabel(index),
            status: run.status,
            tone: toneForRunStatus(run.status),
            detail: run.message,
            note: taskSummary(tasks),
        })),
        progress: runs.flatMap(({ run, tasks }, runIndex) => {
            if (tasks.length > 0)
                return agentTaskProgressLines(tasks);
            return [agentProgressLineModel({
                    key: run.id,
                    agent: runListLabel(runIndex),
                    description: run.message || "(no message)",
                    status: run.status,
                    index: runIndex,
                    total: runs.length,
                    toolUseCount: run.actionCount,
                    elapsedMs: run.updatedAtMs - run.createdAtMs,
                    activity: `artifacts=${run.artifactCount} events=${run.eventCount}`,
                })];
        }),
        footer: "/attach latest | /agents detail attached | /agents step attached",
    };
}
export function agentRunDetailPanelModel(detail) {
    return {
        title: "Agent run",
        subtitle: `${detail.run.status} / actions ${detail.run.actionCount} / artifacts ${detail.run.artifactCount}`,
        rows: detail.tasks.map((task) => taskRow(task)),
        progress: agentTaskProgressLines(detail.tasks),
        preview: [
            `message: ${detail.run.message}`,
            ...detail.events.slice(0, 8).map((event) => `event: ${event.kind} ${summarizePayload(event.payload)}`),
        ],
        footer: "/agents step attached | /agents drain attached",
    };
}
export function agentOperationPanelModel(input) {
    return {
        title: input.title,
        subtitle: input.subtitle,
        rows: [{
                key: input.name,
                name: input.name,
                status: input.status,
                tone: input.tone ?? toneForStatus(input.status),
                detail: input.detail,
                note: input.note ?? "",
            }],
        progress: input.progress,
        preview: input.preview,
        footer: input.footer,
    };
}
export function agentStartedPanelModel(result) {
    return agentOperationPanelModel({
        title: "Agent run started",
        subtitle: "current run",
        name: "agent task",
        status: "queued",
        detail: "agent task queued",
        preview: ["task is queued for the next agent step"],
        footer: "/attach latest | /agents step attached",
    });
}
export function agentStepPanelModel(result) {
    return agentOperationPanelModel({
        title: "Agent step",
        subtitle: "current run",
        name: result.task ? `${result.task.agent} task` : "agent run",
        status: result.status,
        detail: result.message,
        note: result.task ? `${result.task.agent}: ${result.task.title}` : "",
        progress: result.task ? [agentProgressLineModel({
                key: result.task.id,
                agent: result.task.agent,
                description: result.task.title,
                status: result.status,
                toolUseCount: result.result?.execution.results.length,
                elapsedMs: result.task.updatedAtMs - result.task.createdAtMs,
                activity: result.message,
            })] : undefined,
        preview: result.task ? [`${result.task.agent}: ${result.task.title}`, result.task.detail] : undefined,
        footer: "/agents detail attached | /agents drain attached",
    });
}
export function agentDrainPanelModel(result) {
    return agentOperationPanelModel({
        title: "Agent drain",
        subtitle: "current run",
        name: "agent run",
        status: result.status,
        detail: result.message,
        note: `steps=${result.steps.length}`,
        progress: agentStepProgressLines(result.steps),
        preview: result.steps.slice(0, 8).map((step) => `${step.status}${step.task ? ` ${step.task.agent}:${step.task.title}` : ""} ${step.message}`),
        footer: "/agents detail attached",
    });
}
export function agentDaemonPanelModel(result) {
    return agentOperationPanelModel({
        title: "Agent daemon",
        subtitle: result.message,
        name: "daemon",
        status: result.status,
        detail: `${result.runs.length} run${result.runs.length === 1 ? "" : "s"} touched`,
        preview: result.runs.map((run, index) => `${runListLabel(index)} ${run.drain.status} steps=${run.drain.steps.length} ${run.drain.message}`),
        footer: "/agents runs | /agents daemon all",
    });
}
export function agentPanelTabs(model) {
    return [
        { id: "agents", title: "agents", count: model.rows.length, tone: model.rows.length > 0 ? "brand" : "muted" },
        { id: "progress", title: "progress", count: model.progress?.length ?? 0, tone: model.progress?.length ? "brand" : "muted" },
        { id: "detail", title: "detail", count: model.preview?.length ?? 0, tone: model.preview?.length ? "brand" : "muted" },
        { id: "commands", title: "commands", count: agentPanelCommandOptions(model).length, tone: "muted" },
    ];
}
export function agentPanelGroupOptions(model) {
    const groups = new Map();
    for (const row of model.rows) {
        const group = row.status || "unknown";
        const rows = groups.get(group) ?? [];
        rows.push(row);
        groups.set(group, rows);
    }
    return [...groups.entries()].map(([group, rows], index) => ({
        id: group,
        label: group,
        detail: `${rows.length} row${rows.length === 1 ? "" : "s"}`,
        description: rows.slice(0, 4).map((row) => row.name).join(", "),
        selected: index === 0,
        tone: groupTone(rows),
    }));
}
export function agentPanelRowOptions(model, group) {
    return model.rows
        .filter((row) => !group || row.status === group)
        .map((row, index) => ({
        id: row.key,
        label: row.name,
        detail: `${row.status} | ${row.detail}`,
        description: row.note,
        selected: index === 0,
        tone: row.tone,
    }));
}
export function agentPanelCommandOptions(model) {
    const lowerTitle = model.title.toLowerCase();
    const primary = lowerTitle.includes("run")
        ? {
            id: "detail",
            label: "detail",
            detail: "/agents detail attached",
            description: "open task and event detail for the attached or latest run",
            tone: "brand",
        }
        : {
            id: "show",
            label: "show",
            detail: "/agents show <name>",
            description: "open an agent definition with tools and prompt preview",
            tone: "brand",
        };
    return [
        primary,
        {
            id: "start",
            label: "start",
            detail: "/agents start <name> <task>",
            description: "queue a durable agent run that can be attached and stepped",
            tone: "success",
        },
        {
            id: "suggest",
            label: "suggest",
            detail: "/agents suggest <goal>",
            description: "generate a conservative agent plan before creating files",
            tone: "warning",
        },
        {
            id: "runs",
            label: "runs",
            detail: "/agents runs",
            description: "list recent agent runs and task counts",
            tone: "muted",
        },
        {
            id: "validate",
            label: "validate",
            detail: "/agents validate [name]",
            description: "check agent frontmatter, prompt body, and tool policy",
            tone: "muted",
        },
    ];
}
function AgentProgressBlock(props) {
    return (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsx(Text, { color: "gray", children: "progress" }), props.progress.slice(0, 8).map((line) => (_jsx(AgentProgressLine, { model: line, width: props.width }, line.key)))] }));
}
function AgentPreviewBlock(props) {
    return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, children: [_jsx(Text, { color: "gray", children: "agent detail" }), props.lines.slice(0, 8).map((line, index) => (_jsx(Text, { color: "gray", children: truncateCells(`  ${line}`, Math.max(24, props.width - 4)) }, `${index}-${line}`)))] }));
}
function agentPanelStatusLine(model) {
    const groups = agentPanelGroupOptions(model);
    if (groups.length === 0)
        return "no agents";
    return groups.slice(0, 3).map((group) => `${group.id} ${(group.detail ?? "0").split(" ")[0]}`).join(" | ");
}
function groupTone(rows) {
    if (rows.some((row) => row.tone === "error"))
        return "error";
    if (rows.some((row) => row.tone === "warning"))
        return "warning";
    if (rows.some((row) => row.tone === "success"))
        return "success";
    if (rows.some((row) => row.tone === "brand"))
        return "brand";
    return "muted";
}
function taskRow(task) {
    return {
        key: task.id,
        name: `${task.agent} task`,
        status: task.status,
        tone: toneForStatus(task.status),
        detail: `${task.agent}: ${task.title}`,
        note: task.detail,
    };
}
function runListLabel(index) {
    return `run ${index + 1}`;
}
function taskSummary(tasks) {
    if (tasks.length === 0)
        return "tasks=none";
    const counts = new Map();
    for (const task of tasks)
        counts.set(task.status, (counts.get(task.status) ?? 0) + 1);
    return [...counts.entries()].map(([status, count]) => `${status}=${count}`).join(" ");
}
function agentTaskProgressLines(tasks) {
    return tasks.map((task, index) => agentProgressLineModel({
        key: task.id,
        agent: task.agent,
        description: task.title,
        status: task.status,
        index,
        total: tasks.length,
        elapsedMs: task.updatedAtMs - task.createdAtMs,
        activity: task.detail,
    }));
}
function agentStepProgressLines(steps) {
    const taskSteps = steps.filter((step) => Boolean(step.task));
    return taskSteps.map((step, index) => agentProgressLineModel({
        key: step.task.id,
        agent: step.task.agent,
        description: step.task.title,
        status: step.status,
        index,
        total: taskSteps.length,
        toolUseCount: step.result?.execution.results.length,
        elapsedMs: step.task.updatedAtMs - step.task.createdAtMs,
        activity: step.message,
    }));
}
function toneForScope(scope) {
    if (scope === "project")
        return "success";
    if (scope === "user")
        return "brand";
    if (scope === "plugin")
        return "warning";
    return "muted";
}
function toneForRunStatus(status) {
    return toneForStatus(status);
}
function toneForStatus(status) {
    if (status === "succeeded" || status === "ok")
        return "success";
    if (status === "failed" || status === "cancelled")
        return "error";
    if (status === "running" || status === "queued" || status === "paused" || status === "max_steps")
        return "warning";
    return "muted";
}
function previewLines(prompt) {
    return prompt
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line && line !== "---")
        .slice(0, 6);
}
function summarizePayload(payload) {
    const text = redactInternalAgentIds(JSON.stringify(payload ?? {}));
    return text.length > 120 ? `${text.slice(0, 117)}...` : text;
}
function redactInternalAgentIds(text) {
    return text
        .replace(/\brun_[0-9a-f-]{8,}\b/gi, "agent run")
        .replace(/\btask_[0-9a-f-]{8,}\b/gi, "agent task");
}
