use std::path::Path;

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::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;

/// 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(crate) fn lint_package(
    ws: &Workspace<'_>,
    pkg: &Package,
    path: &Path,
    level: LintLevelProduct,
    pkg_stats: &mut ScopedDiagnosticStats<'_>,
    gctx: &GlobalContext,
) -> CargoResult<()> {
    let manifest = pkg.manifest();
    let LintLevelProduct {
        level: lint_level,
        source,
    } = level;

    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 = workspace_rel_path(ws, path);
        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))];

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