// Copyright 2025 The Jujutsu Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt::Debug;
use std::io::Write as _;

use clap::Subcommand;
use jj_lib::backend::CommitId;
use jj_lib::backend::FileId;
use jj_lib::backend::SymlinkId;
use jj_lib::backend::TreeId;
use jj_lib::backend::TreeValue;
use jj_lib::merge::MergedTreeValue;
use jj_lib::op_store::OperationId;
use jj_lib::op_store::ViewId;
use jj_lib::repo_path::RepoPath;
use jj_lib::repo_path::RepoPathBuf;
use tokio::io::AsyncReadExt as _;

use crate::cli_util::CommandHelper;
use crate::cli_util::RevisionArg;
use crate::command_error::CommandError;
use crate::command_error::user_error;
use crate::ui::Ui;

/// Show information about an operation and its view
#[derive(Subcommand, Clone, Debug)]
pub enum DebugObjectArgs {
    Commit(DebugObjectCommitArgs),
    File(DebugObjectFileArgs),
    Operation(DebugObjectOperationArgs),
    Symlink(DebugObjectSymlinkArgs),
    Tree(DebugObjectTreeArgs),
    View(DebugObjectViewArgs),
}

#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectCommitArgs {
    id: String,
}

#[derive(clap::Args, Clone, Debug)]
#[command(group(clap::ArgGroup::new("target").required(true)))]
pub struct DebugObjectFileArgs {
    #[arg(value_hint = clap::ValueHint::FilePath)]
    path: String,

    #[arg(group = "target")]
    id: Option<String>,

    #[arg(long, short, group = "target")]
    revision: Option<RevisionArg>,
}

#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectOperationArgs {
    id: String,
}

#[derive(clap::Args, Clone, Debug)]
pub struct DebugObjectSymlinkArgs {
    #[arg(value_hint = clap::ValueHint::FilePath)]
    path: String,

    #[arg(group = "target")]
    id: Option<String>,

    #[arg(long, short, group = "target")]
    revision: Option<RevisionArg>,
}

#[derive(clap::Args, Clone, Debug)]
#[command(group(clap::ArgGroup::new("target").required(true)))]
pub struct DebugObjectTreeArgs {
    #[arg(value_hint = clap::ValueHint::DirPath)]
    dir: String,

    #[arg(group = "target")]
    id: Option<String>,

    #[arg(long, short, group = "target")]
    revision: Option<RevisionArg>,
}

#[derive(clap::Args, Clone, Debug)]
#[command(group(clap::ArgGroup::new("target").required(true)))]
pub struct DebugObjectViewArgs {
    #[arg(group = "target")]
    id: Option<String>,

    #[arg(long, group = "target")]
    op: Option<String>,
}

pub async fn cmd_debug_object(
    ui: &mut Ui,
    command: &CommandHelper,
    args: &DebugObjectArgs,
) -> Result<(), CommandError> {
    // Resolve the operation without loading the repo, so this command can be used
    // even if e.g. the view object is broken.
    let workspace = command.load_workspace()?;
    let repo_loader = workspace.repo_loader();

    match args {
        DebugObjectArgs::Commit(args) => {
            let id = CommitId::try_from_hex(&args.id)
                .ok_or_else(|| user_error(format!(r#"Invalid hex commit id: "{}""#, args.id)))?;
            let commit = repo_loader.store().get_commit_async(&id).await?;
            writeln!(ui.stdout(), "{:#?}", commit.store_commit())?;
        }
        DebugObjectArgs::File(args) => {
            let path = RepoPathBuf::from_internal_string(&args.path).map_err(user_error)?;
            let id = if let Some(rev) = &args.revision {
                if let Some(Some(TreeValue::File { id, .. })) =
                    get_tree_value(ui, command, rev, &path).await?.as_resolved()
                {
                    id.clone()
                } else {
                    return Err(user_error("The path is not a single file in the commit"));
                }
            } else {
                let file_id = args.id.as_ref().unwrap();
                FileId::try_from_hex(file_id)
                    .ok_or_else(|| user_error(format!(r#"Invalid hex file id: "{file_id}""#)))?
            };
            let mut contents = repo_loader.store().read_file(&path, &id).await?;
            let mut buf = vec![];
            contents.read_to_end(&mut buf).await?;
            ui.stdout().write_all(&buf)?;
        }
        DebugObjectArgs::Operation(args) => {
            let id = OperationId::try_from_hex(&args.id)
                .ok_or_else(|| user_error(format!(r#"Invalid hex operation id: "{}""#, args.id)))?;
            let operation = repo_loader.op_store().read_operation(&id).await?;
            writeln!(ui.stdout(), "{operation:#?}")?;
        }
        DebugObjectArgs::Symlink(args) => {
            let path = RepoPathBuf::from_internal_string(&args.path).map_err(user_error)?;
            let id = if let Some(rev) = &args.revision {
                if let Some(Some(TreeValue::Symlink(id))) =
                    get_tree_value(ui, command, rev, &path).await?.as_resolved()
                {
                    id.clone()
                } else {
                    return Err(user_error("The path is not a single symlink in the commit"));
                }
            } else {
                let symlink_id = args.id.as_ref().unwrap();
                SymlinkId::try_from_hex(symlink_id).ok_or_else(|| {
                    user_error(format!(r#"Invalid hex symlink id: "{symlink_id}""#))
                })?
            };
            let target = repo_loader.store().read_symlink(&path, &id).await?;
            writeln!(ui.stdout(), "{target}")?;
        }
        DebugObjectArgs::Tree(args) => {
            let dir = RepoPathBuf::from_internal_string(&args.dir).map_err(user_error)?;
            let id = if let Some(rev) = &args.revision {
                if let Some(Some(TreeValue::Tree(id))) =
                    get_tree_value(ui, command, rev, &dir).await?.as_resolved()
                {
                    id.clone()
                } else {
                    return Err(user_error("The path is not a single tree in the commit"));
                }
            } else {
                let tree_id = args.id.as_ref().unwrap();
                TreeId::try_from_hex(tree_id)
                    .ok_or_else(|| user_error(format!(r#"Invalid hex tree id: "{tree_id}""#)))?
            };
            let tree = repo_loader.store().get_tree(dir, &id).await?;
            writeln!(ui.stdout(), "{:#?}", tree.data())?;
        }
        DebugObjectArgs::View(args) => {
            let id = if let Some(op_string) = &args.op {
                let workspace_command = command.workspace_helper_no_snapshot(ui)?;
                let op = workspace_command.resolve_single_op(op_string)?;
                op.view_id().clone()
            } else {
                let view_id = args.id.as_ref().unwrap();
                ViewId::try_from_hex(view_id)
                    .ok_or_else(|| user_error(format!(r#"Invalid hex view id: "{view_id}""#)))?
            };
            let view = repo_loader.op_store().read_view(&id).await?;
            writeln!(ui.stdout(), "{view:#?}")?;
        }
    }

    Ok(())
}

async fn get_tree_value(
    ui: &mut Ui,
    command: &CommandHelper,
    rev: &RevisionArg,
    path: &RepoPath,
) -> Result<MergedTreeValue, CommandError> {
    let workspace_command = command.workspace_helper_no_snapshot(ui)?;
    let commit = workspace_command.resolve_single_rev(ui, rev).await?;
    let tree_value = commit.tree().path_value(path).await?;
    Ok(tree_value)
}
