//! Remote operations using API client
//!
//! This module provides utilities for working with the remote API server
//! when running in remote mode (--remote flag).

use crate::api_client::{ApiClient, ApiConfig};
use anyhow::{Context, Result};
use colored::*;

/// Initialize remote API client with configuration
pub fn init_api_client(api_url: Option<String>) -> Result<ApiClient> {
    let mut config = ApiConfig::default();

    if let Some(url) = api_url {
        config.base_url = url;
    }

    config.enabled = true;
    ApiClient::new(config)
}

/// Check API server health and display status
pub async fn check_api_health(client: &ApiClient) -> Result<()> {
    let health = client
        .health_check()
        .await
        .context("Failed to connect to API server")?;

    println!("\n{}", "API Server Status".bold().underline());
    println!(
        "  Status: {}",
        if health.status == "healthy" {
            "healthy".green()
        } else {
            "unhealthy".red()
        }
    );
    println!("  Service: {}", health.service);
    println!("  Version: {}", health.version);
    println!("  Uptime: {}", health.uptime.formatted);
    println!(
        "  Database: {} ({})",
        if health.database.connected {
            "connected".green()
        } else {
            "disconnected".red()
        },
        health.database.db_type
    );
    println!("  Timestamp: {}\n", health.timestamp);

    Ok(())
}

/// Display project list from API
#[allow(dead_code)]
pub async fn display_api_projects(client: &ApiClient) -> Result<()> {
    let projects = client
        .list_projects()
        .await
        .context("Failed to fetch projects from API")?;

    if projects.is_empty() {
        println!("{}", "No projects found on server".italic());
        return Ok(());
    }

    println!("\n{}", "Projects (from API server)".bold().underline());
    for project in projects {
        println!("  {} ({})", project.name.cyan(), project.phase.yellow());
        if let Some(desc) = project.description {
            println!("    {}", desc.dimmed());
        }
        println!("    Status: {}", project.status);
        println!();
    }

    Ok(())
}

/// Display project status from API
#[allow(dead_code)]
pub async fn display_api_status(client: &ApiClient, project_id: &str) -> Result<()> {
    let status = client
        .get_project_status(project_id)
        .await
        .context("Failed to fetch project status from API")?;

    println!(
        "\n{}",
        "Project Status (from API server)".bold().underline()
    );
    println!("  Project ID: {}", project_id);
    println!("  Phase: {}", status.phase.cyan());
    println!("  Completion: {:.1}%", status.completion_percentage);
    println!(
        "  Checklist: {}/{} completed",
        status.checklist_items.completed.to_string().green(),
        status.checklist_items.total
    );
    println!(
        "  Tools: {} enabled, {} disabled",
        status.tools_enabled.to_string().green(),
        status.tools_disabled.to_string().yellow()
    );
    println!();

    Ok(())
}

/// Get current phase from API
#[allow(dead_code)]
pub async fn get_api_phase(client: &ApiClient, project_id: &str) -> Result<String> {
    let phase = client
        .get_current_phase(project_id)
        .await
        .context("Failed to fetch phase from API")?;

    Ok(phase.phase)
}

/// Transition phase via API
#[allow(dead_code)]
pub async fn transition_api_phase(
    client: &ApiClient,
    project_id: &str,
    target_phase: &str,
) -> Result<String> {
    let phase = client
        .transition_phase(project_id, target_phase)
        .await
        .context("Failed to transition phase via API")?;

    println!("✓ Phase transitioned to: {}", phase.phase.cyan().bold());
    println!("  Transitioned at: {}", phase.transitioned_at.dimmed());

    Ok(phase.phase)
}

/// Run security assessment via API
#[allow(dead_code)]
pub async fn run_api_security(client: &ApiClient, project_id: &str) -> Result<()> {
    let assessment = client
        .run_security_assessment(project_id)
        .await
        .context("Failed to run security assessment via API")?;

    println!("\n{}", "Security Assessment Results".bold().underline());
    println!("  Severity: {}", assessment.severity);
    println!("  Date: {}", assessment.assessment_date);
    println!("  Findings: {}", assessment.findings.len());

    if !assessment.findings.is_empty() {
        println!("\n{}", "Findings:".bold());
        for finding in assessment.findings {
            let severity_color = match finding.severity.as_str() {
                "critical" => finding.severity.red(),
                "high" => finding.severity.yellow(),
                _ => finding.severity.normal(),
            };
            println!("  - [{}] {}", severity_color, finding.title);
            println!("    {}", finding.description.dimmed());
        }
    }
    println!();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_init_api_client_default() {
        let result = init_api_client(None);
        assert!(result.is_ok());
        let client = result.unwrap();
        assert!(client.is_enabled());
        assert_eq!(client.base_url(), "http://localhost:3000");
    }

    #[test]
    fn test_init_api_client_custom_url() {
        let result = init_api_client(Some("https://api.example.com".to_string()));
        assert!(result.is_ok());
        let client = result.unwrap();
        assert!(client.is_enabled());
        assert_eq!(client.base_url(), "https://api.example.com");
    }
}
