import { Args } from '@oclif/core';
import { colors, format } from '../../lib/colors.js';
import { getWorkspaceInfo, getAgentStatus, getAllAgentsStatus, formatAgentList, resolveAgentDir } from '../../lib/agents/commands.js';
import { PMOCommand, pmoBaseFlags } from '../../lib/pmo/index.js';
import { shouldOutputJson, outputErrorAsJson, outputSuccessAsJson, createMetadata, } from '../../lib/prompt-json.js';
export default class Status extends PMOCommand {
    static description = 'Show detailed status for a specific agent';
    static examples = [
        '<%= config.bin %> <%= command.id %> agent-1',
        '<%= config.bin %> <%= command.id %>',
    ];
    static args = {
        name: Args.string({
            description: 'Agent name for detailed status',
            required: false,
        }),
    };
    static flags = {
        ...pmoBaseFlags,
    };
    getPMOOptions() {
        return { promptIfMultiple: false };
    }
    async execute() {
        const { args, flags } = await this.parse(Status);
        // Check if JSON output mode is active
        const jsonMode = shouldOutputJson(flags);
        // Get workspace information
        const workspaceInfo = getWorkspaceInfo();
        if (workspaceInfo.agents.length === 0) {
            if (jsonMode) {
                outputErrorAsJson('NO_AGENTS', 'No agents found. Add agents with "prlt agent add"', createMetadata('agent status', flags));
                return;
            }
            this.log(colors.warning('No agents found. Add agents with "prlt agent add"'));
            return;
        }
        let agentName = args.name;
        // In JSON mode with no agent specified, return all agent statuses
        if (jsonMode && !agentName) {
            const allStatuses = getAllAgentsStatus(workspaceInfo);
            outputSuccessAsJson({
                agents: allStatuses,
            }, createMetadata('agent status', flags));
            return;
        }
        // Agent mode config for prompts
        const agentConfig = jsonMode ? { flags, commandName: 'agent status' } : null;
        // Interactive mode if no agent specified
        if (!agentName) {
            // Group agents by type
            const staffAgents = workspaceInfo.agents.filter(a => a.type === 'persistent');
            const tempAgents = workspaceInfo.agents.filter(a => a.type === 'ephemeral');
            // Build choices with command field for JSON mode
            const choices = [];
            for (const agent of staffAgents) {
                choices.push({ name: `👔 ${agent.name}`, value: agent.name, command: `prlt agent status ${agent.name} --machine` });
            }
            for (const agent of tempAgents) {
                choices.push({ name: `⏱️  ${agent.name}`, value: agent.name, command: `prlt agent status ${agent.name} --machine` });
            }
            const { selected } = await this.prompt([{
                    type: 'list',
                    name: 'selected',
                    message: 'Select agent to view status:',
                    choices,
                }], agentConfig);
            agentName = selected;
        }
        await this.showDetailedStatus(workspaceInfo, agentName, jsonMode);
    }
    async showDetailedStatus(workspaceInfo, agentName, jsonMode = false) {
        // Validate agent exists
        const agent = workspaceInfo.agents.find((a) => a.name === agentName);
        if (!agent) {
            this.error(`Agent "${agentName}" not found. Available: ${formatAgentList(workspaceInfo.agents)}`);
        }
        const agentStatus = getAgentStatus(workspaceInfo, agentName);
        // JSON output mode
        if (jsonMode) {
            this.log(JSON.stringify({
                success: true,
                agent: {
                    name: agentName,
                    type: agent.type,
                    exists: agentStatus.exists,
                    path: resolveAgentDir(workspaceInfo, agentName),
                    branch: agentStatus.branch,
                    repositories: agentStatus.repositories.map(r => ({
                        name: r.name,
                        status: r.status,
                        commitsAhead: r.commitsAhead,
                    })),
                    assignedTickets: agentStatus.assignedTickets,
                    completedTickets: agentStatus.completedTickets,
                },
            }, null, 2));
            return;
        }
        this.log(format.title(`🤖 Agent: ${agentName}`));
        // Basic status
        const statusIcon = agentStatus.exists ? '🟢' : '🔴';
        const status = agentStatus.exists ? colors.active('Active') : colors.inactive('Missing');
        this.log(`${statusIcon} Status: ${status}`);
        if (!agentStatus.exists) {
            this.log(colors.error('   Agent directory not found'));
            this.log(colors.textSecondary('   Run "prlt agent add" to recreate'));
            return;
        }
        // Location
        this.log(`📍 Location: ${colors.path(resolveAgentDir(workspaceInfo, agentName))}`);
        // Branch info
        if (agentStatus.branch) {
            this.log(`🌿 Branch: ${colors.warning(agentStatus.branch)}`);
        }
        // Repository status
        this.log(format.subtitle('\n📁 Repositories:'));
        if (agentStatus.repositories.length === 0) {
            this.log(colors.textMuted('   No repositories configured'));
        }
        else {
            for (const repo of agentStatus.repositories) {
                let statusText = '';
                let statusColor = colors.textMuted;
                switch (repo.status) {
                    case 'clean':
                        statusText = 'clean';
                        statusColor = colors.repoClean;
                        break;
                    case 'dirty':
                        statusText = 'dirty';
                        statusColor = colors.repoDirty;
                        break;
                    case 'missing':
                        statusText = 'missing';
                        statusColor = colors.repoMissing;
                        break;
                    default:
                        statusText = repo.status;
                        statusColor = colors.textMuted;
                }
                let repoLine = `   • ${colors.text(repo.name)} (${statusColor(statusText)})`;
                if (repo.commitsAhead > 0) {
                    repoLine += colors.commitsAhead(` ${repo.commitsAhead} commits ahead`);
                }
                this.log(repoLine);
            }
        }
        // Ticket assignments
        if (workspaceInfo.hasPMO) {
            this.log(format.subtitle('\n🎫 Tickets:'));
            if (agentStatus.assignedTickets.length === 0 && agentStatus.completedTickets.length === 0) {
                this.log(colors.textSecondary('   No tickets assigned'));
            }
            else {
                if (agentStatus.assignedTickets.length > 0) {
                    this.log(`   Active: ${colors.primary(agentStatus.assignedTickets.join(', '))}`);
                }
                if (agentStatus.completedTickets.length > 0) {
                    this.log(`   Completed: ${colors.textMuted(agentStatus.completedTickets.length + ' ticket(s)')}`);
                }
            }
        }
    }
}
//# sourceMappingURL=status.js.map