pub use zeroclaw_channels::orchestrator::*;
#[cfg(feature = "channel-matrix")]
pub mod matrix;
#[cfg(feature = "channel-telegram")]
pub mod telegram;
#[cfg(feature = "channel-weixin")]
pub mod weixin;
pub mod session_backend {
    pub use zeroclaw_infra::session_backend::*;
}
pub mod session_sqlite {
    pub use zeroclaw_infra::session_sqlite::*;
}

use crate::config::Config;
use anyhow::Result;

fn resolve_default_config_path(config_arg: Option<&str>) -> String {
    if let Some(path) = config_arg {
        return path.to_string();
    }

    // Check if ~/.zeroclaw/active_workspace.toml exists and read config_dir from it
    if let Some(home) = dirs::home_dir() {
        let active_workspace_path = home.join(".zeroclaw/active_workspace.toml");
        if active_workspace_path.exists() {
            // Try to read config_dir from the file
            if let Ok(content) = std::fs::read_to_string(&active_workspace_path) {
                // Parse simple key = "value" format
                for line in content.lines() {
                    let line = line.trim();
                    if line.starts_with("config_dir") {
                        if let Some(value) = line.splitn(2, '=').nth(1) {
                            let value = value.trim().trim_matches('"').trim_matches('\'');
                            if !value.is_empty() {
                                let config_path = std::path::Path::new(value).join("config.toml");
                                return config_path.to_string_lossy().to_string();
                            }
                        }
                    }
                }
            }
        }

        // Fallback to ~/.zeroclaw/active_workspace.toml if config_dir not found
        return active_workspace_path.to_string_lossy().to_string();
    }

    "zeroclaw.toml".to_string()
}

#[cfg(feature = "channel-weixin")]
async fn weixin_qr_login(config_path: &str) -> Result<()> {
    use zeroclaw_channels::weixin::WeixinChannel;

    tracing::info!("Starting Weixin QR code login...");

    let channel = WeixinChannel::new_with_base_url(
        "https://ilinkai.weixin.qq.com".to_string(),
        String::new(),
        vec!["*".to_string()],
    );

    let result = channel.qr_login_and_save(config_path).await?;

    if result.connected {
        println!("\n✅ Weixin login successful!");
        if let Some(_token) = result.bot_token {
            println!("   Bot token saved to: {}", config_path);
            println!(
                "   Account ID: {}",
                result.account_id.as_deref().unwrap_or("unknown")
            );
        }
    } else {
        println!("\n❌ Weixin login failed: {}", result.message);
    }

    Ok(())
}

pub async fn handle_command(command: crate::ChannelCommands, config: &Config) -> Result<()> {
    match command {
        crate::ChannelCommands::Start => {
            anyhow::bail!("Start must be handled in main.rs (requires async runtime)")
        }
        crate::ChannelCommands::Doctor => {
            anyhow::bail!("Doctor must be handled in main.rs (requires async runtime)")
        }
        crate::ChannelCommands::List => {
            println!("Channels:");
            println!("  ✅ CLI (always available)");
            for (channel, configured) in config.channels.channels() {
                println!(
                    "  {} {}",
                    if configured { "✅" } else { "❌" },
                    channel.name()
                );
            }
            // Notion is a top-level config section, not part of ChannelsConfig
            {
                let notion_configured =
                    config.notion.enabled && !config.notion.database_id.trim().is_empty();
                println!("  {} Notion", if notion_configured { "✅" } else { "❌" });
            }
            if !cfg!(feature = "channel-matrix") {
                println!(
                    "  ℹ️ Matrix channel support is disabled in this build (enable `channel-matrix`)."
                );
            }
            if !cfg!(feature = "channel-lark") {
                println!(
                    "  ℹ️ Lark/Feishu channel support is disabled in this build (enable `channel-lark`)."
                );
            }
            println!("\nTo start channels: zeroclaw channel start");
            println!("To check health:    zeroclaw channel doctor");
            println!("To configure:      zeroclaw onboard");
            Ok(())
        }
        crate::ChannelCommands::Add {
            channel_type,
            config,
        } => {
            #[cfg(feature = "channel-weixin")]
            if channel_type == "weixin" {
                // Weixin uses QR code login, no config needed
                let config_path = resolve_default_config_path(None);
                return Box::pin(weixin_qr_login(&config_path)).await;
            }

            // For other channel types, config is required
            if config.is_none() {
                anyhow::bail!(
                    "Channel type '{channel_type}' requires a configuration. Usage: zeroclaw channel add {channel_type} '<CONFIG_JSON>'"
                );
            }

            anyhow::bail!(
                "Channel type '{channel_type}' — use `zeroclaw onboard` to configure channels"
            );
        }
        crate::ChannelCommands::Remove { name } => {
            anyhow::bail!("Remove channel '{name}' — edit ~/.zeroclaw/config.toml directly");
        }
        crate::ChannelCommands::BindTelegram { identity } => {
            Box::pin(bind_telegram_identity(config, &identity)).await
        }
        crate::ChannelCommands::Send {
            message,
            channel_id,
            recipient,
        } => send_channel_message(config, &channel_id, &recipient, &message).await,
    }
}
