use clap::{Args, Subcommand};

use homeboy::core::deps::{
    self, DependencyStackApplyResult, DependencyStackPlan, DependencyStackStatus, DependencyStatus,
    DependencyUpdateResult,
};

use super::CmdResult;

#[derive(Args)]
pub struct DepsArgs {
    #[command(subcommand)]
    command: DepsCommand,
}

#[derive(Subcommand)]
enum DepsCommand {
    /// Inspect dependency constraints and locked package versions
    Status {
        /// Component ID. When omitted, auto-detected from CWD.
        component: Option<String>,

        /// Limit output to one package.
        #[arg(long, value_name = "PACKAGE")]
        package: Option<String>,

        /// Workspace path to operate on directly.
        #[arg(long, value_name = "PATH")]
        path: Option<String>,
    },
    /// Update one Composer package explicitly
    Update {
        /// Composer package name, e.g. chubes4/block-format-bridge.
        package: String,

        /// Component ID. When omitted, auto-detected from CWD.
        component: Option<String>,

        /// New manifest constraint, e.g. ^0.4.
        #[arg(long, value_name = "CONSTRAINT")]
        to: Option<String>,

        /// Workspace path to operate on directly.
        #[arg(long, value_name = "PATH")]
        path: Option<String>,
    },
    /// Work with declared downstream dependency stacks
    Stack {
        #[command(subcommand)]
        command: DepsStackCommand,
    },
}

#[derive(Subcommand)]
enum DepsStackCommand {
    /// List declared dependency stack edges
    Status,
    /// Plan downstream updates for an upstream component/repo
    Plan {
        /// Upstream component or repository identifier from dependency_stack[].upstream.
        upstream: String,
    },
    /// Run downstream update commands for an upstream component/repo
    Apply {
        /// Upstream component or repository identifier from dependency_stack[].upstream.
        upstream: String,

        /// Print the command plan without running commands.
        #[arg(long)]
        dry_run: bool,
    },
}

pub fn run(args: DepsArgs, _global: &crate::commands::GlobalArgs) -> CmdResult<serde_json::Value> {
    match args.command {
        DepsCommand::Status {
            component,
            package,
            path,
        } => {
            let output: DependencyStatus =
                deps::status(component.as_deref(), path.as_deref(), package.as_deref())?;
            Ok((
                serde_json::to_value(output).map_err(|e| {
                    homeboy::core::Error::internal_json(
                        e.to_string(),
                        Some("serialize deps status".to_string()),
                    )
                })?,
                0,
            ))
        }
        DepsCommand::Update {
            package,
            component,
            to,
            path,
        } => {
            let output: DependencyUpdateResult = deps::update(
                component.as_deref(),
                path.as_deref(),
                &package,
                to.as_deref(),
            )?;
            Ok((
                serde_json::to_value(output).map_err(|e| {
                    homeboy::core::Error::internal_json(
                        e.to_string(),
                        Some("serialize deps update".to_string()),
                    )
                })?,
                0,
            ))
        }
        DepsCommand::Stack { command } => match command {
            DepsStackCommand::Status => {
                let output: DependencyStackStatus = deps::stack_status()?;
                Ok((
                    serde_json::to_value(output).map_err(|e| {
                        homeboy::core::Error::internal_json(
                            e.to_string(),
                            Some("serialize deps stack status".to_string()),
                        )
                    })?,
                    0,
                ))
            }
            DepsStackCommand::Plan { upstream } => {
                let output: DependencyStackPlan = deps::stack_plan(&upstream)?;
                Ok((
                    serde_json::to_value(output).map_err(|e| {
                        homeboy::core::Error::internal_json(
                            e.to_string(),
                            Some("serialize deps stack plan".to_string()),
                        )
                    })?,
                    0,
                ))
            }
            DepsStackCommand::Apply { upstream, dry_run } => {
                let output: DependencyStackApplyResult = deps::stack_apply(&upstream, dry_run)?;
                Ok((
                    serde_json::to_value(output).map_err(|e| {
                        homeboy::core::Error::internal_json(
                            e.to_string(),
                            Some("serialize deps stack apply".to_string()),
                        )
                    })?,
                    0,
                ))
            }
        },
    }
}
