use std::path::PathBuf;

use mentai_agent_core::mentat_policy::{
    MentatDecision, MentatSelfReflectionContext, build_self_reflection_prompt,
    parse_self_reflection_output,
};

#[test]
fn self_reflection_prompt_keeps_recent_24_transcript_items_and_final_reply() {
    let recent_transcript = (0..30)
        .map(|index| format!("assistant: transcript item {index}"))
        .collect::<Vec<_>>();
    let prompt = build_self_reflection_prompt(&MentatSelfReflectionContext {
        raw_user_request: "根据 SPEC.md 实现".to_string(),
        working_dir: PathBuf::from("/tmp/workspace"),
        recent_transcript,
        worker_final_reply: "已经修改完，但还没有验证。".to_string(),
    })
    .expect("build self reflection prompt");

    assert!(prompt.contains("根据 SPEC.md 实现"));
    assert!(prompt.contains("/tmp/workspace"));
    assert!(prompt.contains("assistant: transcript item 29"));
    assert!(prompt.contains("assistant: transcript item 6"));
    assert!(!prompt.contains("assistant: transcript item 5"));
    assert!(prompt.contains("已经修改完，但还没有验证。"));
    assert!(
        prompt.contains("\"decision\":\"ignore\"") || prompt.contains("\"decision\": \"ignore\"")
    );
}

#[test]
fn parse_self_reflection_output_extracts_display_and_decision() {
    let parsed = parse_self_reflection_output(
        "Mentat inspected the completed run and found no strong reason to continue.\n\nMENTAT_SELF_REFLECTION_DECISION_JSON:\n{\"decision\":\"ignore\",\"reason\":\"The completed run does not show a strong unmet execution goal.\"}",
    )
    .expect("parse self reflection output");

    assert_eq!(parsed.decision, MentatDecision::Ignore);
    assert_eq!(
        parsed.reason,
        "The completed run does not show a strong unmet execution goal."
    );
    assert!(
        parsed
            .display_text
            .contains("Mentat inspected the completed run")
    );
}

#[test]
#[ignore = "requires a real codex backend"]
fn real_backend_self_reflection_policy_smoke_test() {
    let decision = mentai_agent_core::mentat_policy::run_self_reflection_decision(
        PathBuf::from(".").as_path(),
        &MentatSelfReflectionContext {
            raw_user_request: "根据 SPEC.md 实现".to_string(),
            working_dir: PathBuf::from("."),
            recent_transcript: vec![
                "user: 根据 SPEC.md 实现".to_string(),
                "assistant: 我已经做了一部分修改，但还没有验证是否满足目标。".to_string(),
            ],
            worker_final_reply: "我已经做了一部分修改，但还没有验证是否满足目标。".to_string(),
        },
    )
    .expect("run self reflection decision");

    assert!(matches!(
        decision.decision,
        MentatDecision::Ignore | MentatDecision::Review
    ));
    assert!(!decision.reason.trim().is_empty());
}
