use std::path::Path;

use cargo_util_schemas::manifest::ProfilePackageSpec;
use cargo_util_terminal::report::AnnotationKind;
use cargo_util_terminal::report::Group;
use cargo_util_terminal::report::Level;
use cargo_util_terminal::report::Origin;
use cargo_util_terminal::report::Patch;
use cargo_util_terminal::report::Snippet;
use tracing::instrument;

use super::SUSPICIOUS;
use crate::CargoResult;
use crate::GlobalContext;
use crate::core::MaybePackage;
use crate::core::Workspace;
use crate::diagnostics::Lint;
use crate::diagnostics::LintLevelProduct;
use crate::diagnostics::ScopedDiagnosticStats;
use crate::diagnostics::get_key_value_span;
use crate::diagnostics::workspace_rel_path;

pub static LINT: &Lint = &Lint {
    name: "blanket_hint_mostly_unused",
    desc: "blanket_hint_mostly_unused lint",
    primary_group: &SUSPICIOUS,
    msrv: Some(super::CARGO_LINTS_MSRV),
    feature_gate: None,
    docs: Some(
        r#"
### What it does
Checks if `hint-mostly-unused` being applied to all dependencies.

### Why it is bad
`hint-mostly-unused` indicates that most of a crate's API surface will go
unused by anything depending on it; this hint can speed up the build by
attempting to minimize compilation time for items that aren't used at all.
Misapplication to crates that don't fit that criteria will slow down the build
rather than speeding it up. It should be selectively applied to dependencies
that meet these criteria. Applying it globally is always a misapplication and
will likely slow down the build.

### Example
```toml
[profile.dev.package."*"]
hint-mostly-unused = true
```

Should instead be:
```toml
[profile.dev.package.huge-mostly-unused-dependency]
hint-mostly-unused = true
```
"#,
    ),
};

#[instrument(skip_all)]
pub(crate) fn lint_workspace(
    ws: &Workspace<'_>,
    maybe_pkg: &MaybePackage,
    path: &Path,
    level: LintLevelProduct,
    pkg_stats: &mut ScopedDiagnosticStats<'_>,
    gctx: &GlobalContext,
) -> CargoResult<()> {
    let LintLevelProduct {
        level: lint_level,
        source,
    } = level;

    let level = lint_level.to_diagnostic_level();
    let manifest_path = workspace_rel_path(ws, path);
    let mut paths = Vec::new();

    if let Some(profiles) = maybe_pkg.profiles() {
        for (profile_name, top_level_profile) in &profiles.0 {
            if let Some(true) = top_level_profile.hint_mostly_unused {
                paths.push((
                    vec!["profile", profile_name.as_str(), "hint-mostly-unused"],
                    true,
                ));
            }

            if let Some(build_override) = &top_level_profile.build_override
                && let Some(true) = build_override.hint_mostly_unused
            {
                paths.push((
                    vec![
                        "profile",
                        profile_name.as_str(),
                        "build-override",
                        "hint-mostly-unused",
                    ],
                    false,
                ));
            }

            if let Some(packages) = &top_level_profile.package
                && let Some(profile) = packages.get(&ProfilePackageSpec::All)
                && let Some(true) = profile.hint_mostly_unused
            {
                paths.push((
                    vec![
                        "profile",
                        profile_name.as_str(),
                        "package",
                        "*",
                        "hint-mostly-unused",
                    ],
                    false,
                ));
            }
        }
    }

    for (i, (path, show_per_pkg_suggestion)) in paths.iter().enumerate() {
        let title = "`hint-mostly-unused` is being blanket applied to all dependencies";
        let help_txt =
            "scope `hint-mostly-unused` to specific packages with a lot of unused object code";

        let mut report = Vec::new();
        let mut primary_group = Group::with_title(level.clone().primary_title(title));

        if let Some(contents) = maybe_pkg.contents()
            && let Some(document) = maybe_pkg.document()
            && let Some(span) = get_key_value_span(document, &path)
            && let Some(table_span) = get_key_value_span(document, &path[..path.len() - 1])
        {
            primary_group = primary_group.element(
                Snippet::source(contents)
                    .path(&manifest_path)
                    .annotation(
                        AnnotationKind::Primary.span(table_span.key.start..table_span.key.end),
                    )
                    .annotation(AnnotationKind::Context.span(span.key.start..span.value.end)),
            );
        } else {
            primary_group = primary_group.element(Origin::path(&manifest_path))
        }

        if *show_per_pkg_suggestion {
            let help_group = Group::with_title(Level::HELP.secondary_title(help_txt));

            report.push(
                if let Some(contents) = maybe_pkg.contents()
                    && let Some(document) = maybe_pkg.document()
                    && let Some(table_span) = get_key_value_span(document, &path[..path.len() - 1])
                {
                    help_group.element(Snippet::source(contents).path(&manifest_path).patch(
                        Patch::new(
                            table_span.key.end..table_span.key.end,
                            ".package.<pkg_name>",
                        ),
                    ))
                } else {
                    help_group.element(Origin::path(&manifest_path))
                },
            );
        } else {
            primary_group = primary_group.element(Level::HELP.message(help_txt));
        }

        if i == 0 {
            primary_group =
                primary_group.element(Level::NOTE.message(LINT.emitted_source(lint_level, source)));
        }

        // The primary group should always be first
        report.insert(0, primary_group);

        pkg_stats.record_lint(lint_level);
        gctx.shell().print_report(&report, lint_level.force())?;
    }

    Ok(())
}
