use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;

use crate::config::Config;
use crate::error::Result;

/// Sink for live progress messages from long-running steps (docker builds,
/// rollout waits, health-check polling). Implementations decide how to render
/// them — e.g. updating a terminal spinner. Must be cheap and non-blocking.
pub trait ProgressReporter: Send + Sync {
    /// Replace the current progress message for the running step.
    fn set_message(&self, message: &str);
}

/// Shared context available to every step during validation/execution/rollback.
pub struct StepContext {
    /// Fully resolved release configuration.
    pub config: Config,
    /// Whether the current pipeline run is a dry-run.
    pub dry_run: bool,
    /// Cross-step state bag for lightweight value passing.
    pub state: HashMap<String, String>,
    /// Optional live progress sink for long-running operations.
    pub progress: Option<Arc<dyn ProgressReporter>>,
}

impl StepContext {
    /// Report step progress if a reporter is attached; no-op otherwise.
    pub fn report_progress(&self, message: &str) {
        if let Some(ref reporter) = self.progress {
            reporter.set_message(message);
        }
    }
}

#[derive(Debug, Clone)]
/// Result payload emitted by each successful step execution.
pub struct StepOutput {
    /// Final step status.
    pub status: StepStatus,
    /// Human-readable message rendered in CLI output.
    pub message: String,
    /// Execution duration in milliseconds.
    pub duration_ms: u64,
    /// Detailed dry-run information (file changes, etc.).
    pub dry_run_details: Option<DryRunDetails>,
}

#[derive(Debug, Clone)]
/// Detailed information for dry-run mode.
pub struct DryRunDetails {
    /// File operations that would be performed.
    pub file_changes: Vec<FileChange>,
    /// Docker operations preview.
    pub docker_preview: Option<DockerPreview>,
    /// Additional notes for user.
    pub notes: Vec<String>,
}

#[derive(Debug, Clone)]
/// Represents a file change (create, modify, delete).
pub struct FileChange {
    pub path: String,
    pub operation: FileOperation,
    pub diff: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileOperation {
    Create,
    Modify,
    Delete,
}

#[derive(Debug, Clone)]
/// Docker-specific preview information.
pub struct DockerPreview {
    pub image_name: String,
    pub tags: Vec<String>,
    pub build_args: Vec<(String, String)>,
    pub layers_estimate: Option<usize>,
}

impl StepOutput {
    pub fn ok(message: impl Into<String>) -> Self {
        Self {
            status: StepStatus::Success,
            message: message.into(),
            duration_ms: 0,
            dry_run_details: None,
        }
    }

    pub fn skipped(message: impl Into<String>) -> Self {
        Self {
            status: StepStatus::Skipped,
            message: message.into(),
            duration_ms: 0,
            dry_run_details: None,
        }
    }

    pub fn with_dry_run_details(mut self, details: DryRunDetails) -> Self {
        self.dry_run_details = Some(details);
        self
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Unified step status values used in run summaries.
pub enum StepStatus {
    Success,
    Skipped,
    Failed,
}

impl std::fmt::Display for StepStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StepStatus::Success => write!(f, "✓"),
            StepStatus::Skipped => write!(f, "⊘"),
            StepStatus::Failed => write!(f, "✗"),
        }
    }
}

pub mod cloudfront;
pub mod docker;
pub mod git;
pub mod github;
pub mod health;
pub mod kubernetes;
pub mod notify;

#[async_trait]
/// Contract implemented by all release pipeline steps.
pub trait Step: Send + Sync {
    /// Stable step name used in output and logs.
    fn name(&self) -> &str;
    /// Human-readable summary of what the step does.
    fn description(&self) -> &str;
    /// Validate prerequisites before execution starts.
    async fn validate(&self, ctx: &StepContext) -> Result<()>;
    /// Execute the step in normal mode.
    async fn execute(&self, ctx: &StepContext) -> Result<StepOutput>;
    /// Simulate execution without changing external systems.
    async fn dry_run(&self, ctx: &StepContext) -> Result<StepOutput>;

    /// Attempt to rollback effects of a previously successful execution.
    ///
    /// Default implementation is a no-op for steps that are read-only.
    async fn rollback(&self, _ctx: &StepContext) -> Result<()> {
        Ok(())
    }
}
