use std::path::Path;

use cargo_util_schemas::manifest::TomlToolLints;
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::Snippet;
use tracing::instrument;

use super::TEST_DUMMY_UNSTABLE;
use crate::CargoResult;
use crate::GlobalContext;
use crate::core::Feature;
use crate::core::Package;
use crate::diagnostics::DiagnosticStats;
use crate::diagnostics::Lint;
use crate::diagnostics::LintLevel;
use crate::diagnostics::get_key_value_span;
use crate::diagnostics::rel_cwd_manifest_path;

/// This lint is only to be used for testing purposes
pub static LINT: &Lint = &Lint {
    name: "im_a_teapot",
    desc: "`im_a_teapot` is specified",
    primary_group: &TEST_DUMMY_UNSTABLE,
    msrv: None,
    feature_gate: Some(Feature::test_dummy_unstable()),
    docs: None,
};

#[instrument(skip_all)]
pub fn check_im_a_teapot(
    pkg: &Package,
    path: &Path,
    pkg_lints: &TomlToolLints,
    stats: &mut DiagnosticStats,
    gctx: &GlobalContext,
) -> CargoResult<()> {
    let manifest = pkg.manifest();
    let (lint_level, source) =
        LINT.level(pkg_lints, pkg.rust_version(), manifest.unstable_features());

    if lint_level == LintLevel::Allow {
        return Ok(());
    }

    if manifest
        .normalized_toml()
        .package()
        .is_some_and(|p| p.im_a_teapot.is_some())
    {
        let level = lint_level.to_diagnostic_level();
        let manifest_path = rel_cwd_manifest_path(path, gctx);
        let emitted_source = LINT.emitted_source(lint_level, source);

        let mut desc = Group::with_title(level.primary_title(LINT.desc));

        if let Some(document) = manifest.document()
            && let Some(contents) = manifest.contents()
        {
            let span = get_key_value_span(document, &["package", "im-a-teapot"]).unwrap();

            desc = desc.element(
                Snippet::source(contents)
                    .path(&manifest_path)
                    .annotation(AnnotationKind::Primary.span(span.key.start..span.value.end)),
            );
        } else {
            desc = desc.element(Origin::path(&manifest_path));
        }

        let report = &[desc.element(Level::NOTE.message(&emitted_source))];

        stats.record_lint(lint_level);
        gctx.shell().print_report(report, lint_level.force())?;
    }
    Ok(())
}
