use crate::config::{AppConfig, Environment};
use crate::error::Result;
use crate::output::{create_table, is_json_output, output_success, print_section, print_title, Timer};
use crate::ssh::SSHClient;
use clap::{Args, Subcommand};
use colored::*;
use serde::{Deserialize, Serialize};
use serde_json::json;

#[derive(Args)]
pub struct InfraCommand {
    #[command(subcommand)]
    command: InfraSubcommand,
}

#[derive(Subcommand)]
enum InfraSubcommand {
    /// EC2 instance information
    Ec2(Ec2Command),
    /// Docker container resources
    Docker(DockerCommand),
    /// Disk usage information
    Disk(DiskCommand),
    /// Network configuration
    Network(NetworkCommand),
    /// GitHub Actions Runner status
    Runner(RunnerCommand),
}

#[derive(Args)]
struct Ec2Command {
    /// Environment (production/stage/development)
    #[arg(long)]
    env: Option<String>,

    /// Output in JSON format
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct DockerCommand {
    /// Environment (production/stage/development)
    #[arg(long)]
    env: Option<String>,

    /// Output in JSON format
    #[arg(long)]
    json: bool,
}

#[derive(Args)]
struct DiskCommand {
    /// Environment (production/stage/development)
    #[arg(long)]
    env: Option<String>,

    /// Show detailed information
    #[arg(long)]
    details: bool,

    /// Output in JSON format
    #[arg(long)]
    json: bool,
}

impl InfraCommand {
    pub async fn execute(&self, config: &AppConfig) -> Result<()> {
        match &self.command {
            InfraSubcommand::Ec2(cmd) => cmd.execute(config).await,
            InfraSubcommand::Docker(cmd) => cmd.execute(config).await,
            InfraSubcommand::Disk(cmd) => cmd.execute(config).await,
            InfraSubcommand::Network(cmd) => cmd.execute(config).await,
            InfraSubcommand::Runner(cmd) => cmd.execute(config).await,
        }
    }
}

impl Ec2Command {
    async fn execute(&self, config: &AppConfig) -> Result<()> {
        let mut timer = Timer::new();

        let env = self
            .env
            .as_ref()
            .and_then(|e| Environment::from_str(e))
            .unwrap_or_else(|| config.get_environment());

        if !is_json_output() && !self.json {
            print_title(&format!("🖥️  EC2 实例信息 - {} 环境", env.as_str()));
        }

        let mut ssh_client = SSHClient::new(config, Some(env));
        ssh_client.connect().await?;
        timer.step("SSH 连接");

        // 获取系统信息
        let hostname = ssh_client
            .execute_command("hostname", true, None)
            .await?
            .stdout
            .trim()
            .to_string();

        let uptime = ssh_client
            .execute_command("uptime", true, None)
            .await?
            .stdout
            .trim()
            .to_string();

        let cpu_info = ssh_client
            .execute_command("grep -c processor /proc/cpuinfo", true, None)
            .await?
            .stdout
            .trim()
            .to_string();

        let mem_info = ssh_client
            .execute_command("free -h", true, None)
            .await?
            .stdout;

        timer.step("系统信息");

        if is_json_output() || self.json {
            output_success(json!({
                "environment": env.as_str(),
                "hostname": hostname,
                "uptime": uptime,
                "cpu_cores": cpu_info,
                "memory": mem_info,
                "_timing": if crate::output::is_timing_enabled() {
                    Some(timer.get_timing_data())
                } else {
                    None
                }
            }))?;
        } else {
            print_section("基本信息:");
            println!("  主机名: {}", hostname.yellow());
            println!("  运行时间: {}", uptime);
            println!("  CPU 核心数: {}", cpu_info);
            println!("\n{}", "内存信息:".white().bold());
            println!("{}", mem_info);

            timer.print_summary();
        }

        Ok(())
    }
}

impl DockerCommand {
    async fn execute(&self, config: &AppConfig) -> Result<()> {
        let env = self
            .env
            .as_ref()
            .and_then(|e| Environment::from_str(e))
            .unwrap_or_else(|| config.get_environment());

        if !is_json_output() && !self.json {
            print_title(&format!("🐳 Docker 容器资源 - {} 环境", env.as_str()));
        }

        let mut ssh_client = SSHClient::new(config, Some(env));
        ssh_client.connect().await?;

        let stats = ssh_client
            .execute_command(
                "docker stats --no-stream --format \"{{.Name}}\\t{{.CPUPerc}}\\t{{.MemUsage}}\\t{{.NetIO}}\"",
                true,
                None,
            )
            .await?;

        if is_json_output() || self.json {
            let containers: Vec<_> = stats
                .stdout
                .lines()
                .filter(|line| !line.trim().is_empty())
                .map(|line| {
                    let parts: Vec<&str> = line.split('\t').collect();
                    json!({
                        "name": parts.get(0).unwrap_or(&""),
                        "cpu": parts.get(1).unwrap_or(&""),
                        "memory": parts.get(2).unwrap_or(&""),
                        "network": parts.get(3).unwrap_or(&""),
                    })
                })
                .collect();

            output_success(json!({
                "environment": env.as_str(),
                "containers": containers,
            }))?;
        } else {
            let mut table = create_table();
            table.set_header(vec!["容器名称", "CPU %", "内存使用", "网络 I/O"]);

            for line in stats.stdout.lines() {
                if line.trim().is_empty() {
                    continue;
                }

                let parts: Vec<&str> = line.split('\t').collect();
                if parts.len() >= 4 {
                    table.add_row(vec![parts[0], parts[1], parts[2], parts[3]]);
                }
            }

            println!("{}\n", table);
        }

        Ok(())
    }
}

impl DiskCommand {
    async fn execute(&self, config: &AppConfig) -> Result<()> {
        let env = self
            .env
            .as_ref()
            .and_then(|e| Environment::from_str(e))
            .unwrap_or_else(|| config.get_environment());

        if !is_json_output() && !self.json {
            print_title(&format!("💾 磁盘使用情况 - {} 环境", env.as_str()));
        }

        let mut ssh_client = SSHClient::new(config, Some(env));
        ssh_client.connect().await?;

        let disk_usage = ssh_client
            .execute_command("df -h", true, None)
            .await?;

        if is_json_output() || self.json {
            output_success(json!({
                "environment": env.as_str(),
                "disk_usage": disk_usage.stdout,
            }))?;
        } else {
            println!("{}", disk_usage.stdout);
            println!();
        }

        Ok(())
    }
}

// ============================================================================
// Network Command
// ============================================================================

#[derive(Args)]
struct NetworkCommand {
    /// Environment (production/stage/development)
    #[arg(long)]
    env: Option<String>,

    /// Output in JSON format
    #[arg(long)]
    json: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct NetworkInterface {
    name: String,
    ipv4: Option<String>,
    ipv6: Option<String>,
    mac: Option<String>,
    state: String,
    mtu: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct DockerNetworkInfo {
    name: String,
    driver: String,
    scope: String,
    subnet: Option<String>,
    gateway: Option<String>,
    containers: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ContainerNetwork {
    container_id: String,
    container_name: String,
    network_mode: String,
    ipv4_address: Option<String>,
    ports: Vec<String>,
}

impl NetworkCommand {
    async fn execute(&self, config: &AppConfig) -> Result<()> {
        let mut timer = Timer::new();

        let env = self
            .env
            .as_ref()
            .and_then(|e| Environment::from_str(e))
            .unwrap_or_else(|| config.get_environment());

        if !is_json_output() && !self.json {
            print_title(&format!("🌐 网络配置 - {} 环境", env.as_str()));
        }

        let mut ssh_client = SSHClient::new(config, Some(env));
        ssh_client.connect().await?;
        timer.step("SSH 连接");

        // 获取主机网络接口
        let ip_result = ssh_client
            .execute_command("ip -o addr show", true, None)
            .await?;

        let mut interfaces: Vec<NetworkInterface> = Vec::new();

        for line in ip_result.stdout.lines() {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 4 {
                let if_name = parts[1].trim_end_matches(':');
                let addr_type = parts[2];
                let address = parts[3];

                // 跳过 loopback
                if if_name == "lo" {
                    continue;
                }

                // 查找或创建接口记录
                let iface = interfaces.iter_mut().find(|i| i.name == if_name);

                if let Some(iface) = iface {
                    if addr_type == "inet" {
                        iface.ipv4 = Some(address.split('/').next().unwrap_or(address).to_string());
                    } else if addr_type == "inet6" {
                        iface.ipv6 = Some(address.split('/').next().unwrap_or(address).to_string());
                    }
                } else {
                    let mut new_iface = NetworkInterface {
                        name: if_name.to_string(),
                        ipv4: None,
                        ipv6: None,
                        mac: None,
                        state: "unknown".to_string(),
                        mtu: None,
                    };

                    if addr_type == "inet" {
                        new_iface.ipv4 = Some(address.split('/').next().unwrap_or(address).to_string());
                    } else if addr_type == "inet6" {
                        new_iface.ipv6 = Some(address.split('/').next().unwrap_or(address).to_string());
                    }

                    interfaces.push(new_iface);
                }
            }
        }

        // 批量获取接口状态 (一次 SSH 调用)
        let link_result = ssh_client
            .execute_command("ip link show", true, None)
            .await?;

        for iface in &mut interfaces {
            // 解析 ip link show 输出
            let iface_pattern = format!("{}: ", iface.name);
            for line in link_result.stdout.lines() {
                if line.contains(&iface_pattern) || line.contains(&format!("{}@", iface.name)) {
                    // 解析状态
                    if let Some(state_match) = line.split("state ").nth(1) {
                        iface.state = state_match.split_whitespace().next().unwrap_or("unknown").to_string();
                    }
                    // 解析 MTU
                    if let Some(mtu_match) = line.split("mtu ").nth(1) {
                        iface.mtu = Some(mtu_match.split_whitespace().next().unwrap_or("").to_string());
                    }
                }
                // MAC 地址在下一行
                if line.contains("link/ether") {
                    if let Some(mac_match) = line.split("link/ether ").nth(1) {
                        let mac = mac_match.split_whitespace().next().unwrap_or("");
                        // 检查是否属于当前接口 (需要跟踪上下文)
                        if !mac.is_empty() && iface.mac.is_none() {
                            iface.mac = Some(mac.to_string());
                        }
                    }
                }
            }
        }

        timer.step("主机网络");

        // 获取 Docker 网络信息
        let docker_networks_result = ssh_client
            .execute_command(
                "docker network ls --format \"{{.Name}}\t{{.Driver}}\t{{.Scope}}\"",
                true,
                None,
            )
            .await?;

        let mut docker_networks: Vec<DockerNetworkInfo> = Vec::new();

        for line in docker_networks_result.stdout.lines() {
            if line.trim().is_empty() {
                continue;
            }

            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 3 {
                let network_name = parts[0];

                // 获取网络详细信息
                let inspect_result = ssh_client
                    .execute_command(&format!("docker network inspect {}", network_name), true, None)
                    .await;

                if let Ok(inspect) = inspect_result {
                    if let Ok(network_data) = serde_json::from_str::<Vec<serde_json::Value>>(&inspect.stdout) {
                        if let Some(data) = network_data.first() {
                            let subnet = data["IPAM"]["Config"]
                                .as_array()
                                .and_then(|c| c.first())
                                .and_then(|c| c["Subnet"].as_str())
                                .map(|s| s.to_string());

                            let gateway = data["IPAM"]["Config"]
                                .as_array()
                                .and_then(|c| c.first())
                                .and_then(|c| c["Gateway"].as_str())
                                .map(|s| s.to_string());

                            let containers = data["Containers"]
                                .as_object()
                                .map(|c| c.len())
                                .unwrap_or(0);

                            docker_networks.push(DockerNetworkInfo {
                                name: network_name.to_string(),
                                driver: parts[1].to_string(),
                                scope: parts[2].to_string(),
                                subnet,
                                gateway,
                                containers,
                            });
                            continue;
                        }
                    }
                }

                // 回退：使用基本信息
                docker_networks.push(DockerNetworkInfo {
                    name: network_name.to_string(),
                    driver: parts[1].to_string(),
                    scope: parts[2].to_string(),
                    subnet: None,
                    gateway: None,
                    containers: 0,
                });
            }
        }

        timer.step("Docker 网络");

        // 获取容器网络信息
        let containers_result = ssh_client
            .execute_command(
                "docker ps --format \"{{.ID}}\t{{.Names}}\"",
                true,
                None,
            )
            .await?;

        let mut container_networks: Vec<ContainerNetwork> = Vec::new();

        for line in containers_result.stdout.lines() {
            if line.trim().is_empty() {
                continue;
            }

            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 2 {
                let container_id = parts[0];
                let container_name = parts[1];

                let inspect_result = ssh_client
                    .execute_command(&format!("docker inspect {}", container_id), true, None)
                    .await;

                if let Ok(inspect) = inspect_result {
                    if let Ok(container_data) = serde_json::from_str::<Vec<serde_json::Value>>(&inspect.stdout) {
                        if let Some(data) = container_data.first() {
                            let network_mode = data["HostConfig"]["NetworkMode"]
                                .as_str()
                                .unwrap_or("default")
                                .to_string();

                            // 获取第一个网络的 IP
                            let networks = data["NetworkSettings"]["Networks"].as_object();
                            let ipv4_address = networks
                                .and_then(|n| n.values().next())
                                .and_then(|n| n["IPAddress"].as_str())
                                .map(|s| s.to_string());

                            // 端口映射
                            let mut ports: Vec<String> = Vec::new();
                            if let Some(port_bindings) = data["HostConfig"]["PortBindings"].as_object() {
                                for (container_port, host_bindings) in port_bindings {
                                    if let Some(bindings) = host_bindings.as_array() {
                                        for binding in bindings {
                                            if let Some(host_port) = binding["HostPort"].as_str() {
                                                ports.push(format!("{}→{}", host_port, container_port));
                                            }
                                        }
                                    }
                                }
                            }

                            container_networks.push(ContainerNetwork {
                                container_id: container_id.to_string(),
                                container_name: container_name.to_string(),
                                network_mode,
                                ipv4_address,
                                ports,
                            });
                        }
                    }
                }
            }
        }

        timer.step("容器网络");

        // 输出结果
        if is_json_output() || self.json {
            output_success(json!({
                "environment": env.as_str(),
                "interfaces": interfaces,
                "docker_networks": docker_networks,
                "container_networks": container_networks,
                "_timing": if crate::output::is_timing_enabled() {
                    Some(timer.get_timing_data())
                } else {
                    None
                }
            }))?;
        } else {
            // 主机网络接口
            print_section("主机网络接口");
            if !interfaces.is_empty() {
                let mut table = create_table();
                table.set_header(vec!["接口", "状态", "IPv4", "IPv6", "MTU"]);

                for iface in &interfaces {
                    let state_display = match iface.state.as_str() {
                        "UP" => iface.state.green().to_string(),
                        "DOWN" => iface.state.red().to_string(),
                        _ => iface.state.yellow().to_string(),
                    };

                    table.add_row(vec![
                        &iface.name,
                        &state_display,
                        iface.ipv4.as_deref().unwrap_or("N/A"),
                        iface.ipv6.as_deref().unwrap_or("N/A"),
                        iface.mtu.as_deref().unwrap_or("N/A"),
                    ]);
                }
                println!("{}\n", table);
            } else {
                println!("{}\n", "未找到网络接口".yellow());
            }

            // Docker 网络
            print_section("Docker 网络");
            if !docker_networks.is_empty() {
                let mut table = create_table();
                table.set_header(vec!["网络名称", "驱动", "范围", "子网", "网关", "容器数"]);

                for network in &docker_networks {
                    table.add_row(vec![
                        &network.name,
                        &network.driver,
                        &network.scope,
                        network.subnet.as_deref().unwrap_or("N/A"),
                        network.gateway.as_deref().unwrap_or("N/A"),
                        &network.containers.to_string(),
                    ]);
                }
                println!("{}\n", table);
            } else {
                println!("{}\n", "未找到 Docker 网络".yellow());
            }

            // 容器网络
            print_section("容器网络");
            if !container_networks.is_empty() {
                let mut table = create_table();
                table.set_header(vec!["容器名称", "网络模式", "IP 地址", "端口映射"]);

                for container in &container_networks {
                    let ports_display = if container.ports.is_empty() {
                        "N/A".to_string()
                    } else {
                        container.ports.join(", ")
                    };

                    table.add_row(vec![
                        &container.container_name,
                        &container.network_mode,
                        container.ipv4_address.as_deref().unwrap_or("N/A"),
                        &ports_display,
                    ]);
                }
                println!("{}\n", table);
            } else {
                println!("{}\n", "未找到运行中的容器".yellow());
            }

            // 提示
            println!("{}", "💡 提示:".bright_black());
            println!("{}", "  - 使用 optima-ops services status 查看容器详细状态".bright_black());
            println!("{}", "  - 使用 optima-ops services inspect <service> 查看容器网络配置".bright_black());

            timer.print_summary();
        }

        Ok(())
    }
}

// ============================================================================
// Runner Command
// ============================================================================

#[derive(Args)]
struct RunnerCommand {
    /// Environment (production/stage/development)
    #[arg(long)]
    env: Option<String>,

    /// Number of log lines to show (default: 20)
    #[arg(long, default_value = "20")]
    logs: usize,

    /// Output in JSON format
    #[arg(long)]
    json: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RunnerInfo {
    name: String,
    status: String,
    active_since: Option<String>,
    version: Option<String>,
    pid: Option<u32>,
    memory_usage: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ServiceInfo {
    unit_name: String,
    load_state: String,
    active_state: String,
    sub_state: String,
    main_pid: Option<u32>,
}

impl RunnerCommand {
    async fn execute(&self, config: &AppConfig) -> Result<()> {
        let mut timer = Timer::new();

        let env = self
            .env
            .as_ref()
            .and_then(|e| Environment::from_str(e))
            .unwrap_or_else(|| config.get_environment());

        // GitHub Runners 运行在 shared EC2 上
        // 服务名是 optima-prod-host 或 optima-stage-host
        let runner_name = match env {
            Environment::Production => "optima-prod-host",
            Environment::Stage => "optima-stage-host",
            Environment::Shared => "optima-prod-host", // shared 环境默认看 prod runner
            Environment::Development => "optima-dev-host",
        };

        let service_name = format!("actions.runner.Optima-Chat.{}.service", runner_name);

        // Runner 都在 shared EC2 上运行
        let ssh_env = Environment::Shared;

        if !is_json_output() && !self.json {
            print_title(&format!("🏃 GitHub Actions Runner - {} (运行在 shared EC2)", runner_name));
        }

        let mut ssh_client = SSHClient::new(config, Some(ssh_env));
        ssh_client.connect().await?;
        timer.step("SSH 连接");

        let mut runner_info = RunnerInfo {
            name: runner_name.to_string(),
            status: "unknown".to_string(),
            active_since: None,
            version: None,
            pid: None,
            memory_usage: None,
        };

        let mut service_info = ServiceInfo {
            unit_name: service_name.clone(),
            load_state: String::new(),
            active_state: String::new(),
            sub_state: String::new(),
            main_pid: None,
        };

        // 获取服务状态
        let status_result = ssh_client
            .execute_command(&format!("systemctl show {} --no-pager", service_name), true, None)
            .await;

        if let Ok(status) = status_result {
            for line in status.stdout.lines() {
                if let Some((key, value)) = line.split_once('=') {
                    match key {
                        "LoadState" => service_info.load_state = value.to_string(),
                        "ActiveState" => {
                            service_info.active_state = value.to_string();
                            runner_info.status = if value == "active" {
                                "running".to_string()
                            } else {
                                "stopped".to_string()
                            };
                        }
                        "SubState" => service_info.sub_state = value.to_string(),
                        "MainPID" => {
                            if let Ok(pid) = value.parse::<u32>() {
                                if pid > 0 {
                                    service_info.main_pid = Some(pid);
                                    runner_info.pid = Some(pid);
                                }
                            }
                        }
                        "ActiveEnterTimestamp" => {
                            if !value.is_empty() && value != "0" {
                                runner_info.active_since = Some(value.to_string());
                            }
                        }
                        _ => {}
                    }
                }
            }
        } else {
            runner_info.status = "not_found".to_string();
        }

        timer.step("服务状态");

        // 如果运行中，获取额外信息
        if runner_info.status == "running" {
            // 获取内存使用
            if let Some(pid) = runner_info.pid {
                let mem_result = ssh_client
                    .execute_command(
                        &format!("ps -p {} -o rss= 2>/dev/null", pid),
                        true,
                        None,
                    )
                    .await;

                if let Ok(mem) = mem_result {
                    if let Ok(rss) = mem.stdout.trim().parse::<f64>() {
                        runner_info.memory_usage = Some(format!("{:.1} MB", rss / 1024.0));
                    }
                }
            }

            // 尝试获取版本
            let version_result = ssh_client
                .execute_command(
                    "cat /opt/actions-runner/.runner 2>/dev/null | grep -o '\"gitHubRunnerVersion\":\"[^\"]*\"' | cut -d'\"' -f4",
                    true,
                    None,
                )
                .await;

            if let Ok(version) = version_result {
                let v = version.stdout.trim();
                if !v.is_empty() {
                    runner_info.version = Some(v.to_string());
                }
            }
        }

        timer.step("Runner 信息");

        // 获取日志
        let logs_result = ssh_client
            .execute_command(
                &format!(
                    "journalctl -u {} -n {} --no-pager --output=short-iso 2>/dev/null",
                    service_name, self.logs
                ),
                true,
                None,
            )
            .await;

        let logs: Vec<String> = logs_result
            .map(|r| {
                r.stdout
                    .lines()
                    .filter(|l| !l.trim().is_empty())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_else(|_| vec!["日志获取失败".to_string()]);

        timer.step("获取日志");

        // 输出结果
        if is_json_output() || self.json {
            output_success(json!({
                "environment": env.as_str(),
                "runner": runner_info,
                "service": service_info,
                "logs": logs,
                "_timing": if crate::output::is_timing_enabled() {
                    Some(timer.get_timing_data())
                } else {
                    None
                }
            }))?;
        } else {
            // Runner 信息
            print_section("Runner 信息");
            let mut table = create_table();

            let status_display = match runner_info.status.as_str() {
                "running" => "运行中".green().to_string(),
                "stopped" => "已停止".red().to_string(),
                "not_found" => "未找到".yellow().to_string(),
                _ => runner_info.status.clone(),
            };

            table.add_row(vec!["Runner 名称", &runner_info.name]);
            table.add_row(vec!["状态", &status_display]);
            table.add_row(vec!["服务名称", &service_info.unit_name]);
            table.add_row(vec!["版本", runner_info.version.as_deref().unwrap_or("N/A")]);
            table.add_row(vec!["进程 ID", &runner_info.pid.map(|p| p.to_string()).unwrap_or_else(|| "N/A".to_string())]);
            table.add_row(vec!["内存使用", runner_info.memory_usage.as_deref().unwrap_or("N/A")]);
            table.add_row(vec!["运行时间", runner_info.active_since.as_deref().unwrap_or("N/A")]);

            println!("{}\n", table);

            // Systemd 服务详情
            print_section("Systemd 服务");
            let mut service_table = create_table();
            service_table.add_row(vec!["Load State", &service_info.load_state]);
            service_table.add_row(vec!["Active State", &service_info.active_state]);
            service_table.add_row(vec!["Sub State", &service_info.sub_state]);
            service_table.add_row(vec!["Main PID", &service_info.main_pid.map(|p| p.to_string()).unwrap_or_else(|| "N/A".to_string())]);

            println!("{}\n", service_table);

            // 显示日志
            if !logs.is_empty() {
                print_section(&format!("最近 {} 行日志", self.logs));
                for log_line in &logs {
                    let display_line = if log_line.to_lowercase().contains("error") {
                        log_line.red().to_string()
                    } else if log_line.to_lowercase().contains("warning") {
                        log_line.yellow().to_string()
                    } else if log_line.to_lowercase().contains("running job") {
                        log_line.cyan().to_string()
                    } else {
                        log_line.bright_black().to_string()
                    };
                    println!("{}", display_line);
                }
                println!();
            }

            // 状态警告
            if runner_info.status != "running" {
                println!("{}", "⚠️  Runner 未运行".red().bold());
                println!("{}", "排查步骤:".bright_black());
                println!("{}", format!("  1. sudo systemctl status {}", service_info.unit_name).bright_black());
                println!("{}", format!("  2. sudo systemctl start {}", service_info.unit_name).bright_black());
                println!("{}", format!("  3. sudo journalctl -u {} -n 50", service_info.unit_name).bright_black());
                println!();
            }

            // 提示
            println!("{}", "💡 提示:".bright_black());
            println!("{}", "  - 使用 --logs 50 查看更多日志".bright_black());
            println!("{}", "  - 使用 optima-ops deploy status <service> 查看部署历史".bright_black());

            timer.print_summary();
        }

        Ok(())
    }
}
