//! Prompt templates and engineering for Claude API.

use crate::claude::ai::{PromptStyle, ResponseFormat};
use crate::data::context::{CommitContext, VerbosityLevel, WorkPattern};

/// Suffix appended to the system prompt when the response is constrained
/// by a JSON Schema (i.e. [`ResponseFormat::JsonSchema`]).
///
/// Existing prompts ask the model to format the response as YAML in a
/// fenced or bare block. When `claude -p --json-schema` is in play, the
/// CLI re-prompts until the model produces a JSON object validating
/// against the supplied schema. The original YAML instructions are then
/// actively misleading: they cost a re-prompt as the model first emits
/// YAML and the CLI rejects it.
///
/// This suffix overrides the format directive without rewriting the
/// surrounding semantic content. It is intentionally placed at the end
/// of the system prompt so its instructions are the most-recent (and
/// thus most-attended-to) text for the model.
pub const JSON_SCHEMA_RESPONSE_OVERRIDE: &str = "\n\n=== STRUCTURED OUTPUT OVERRIDE ===\n\
DISREGARD any previous instructions to format your response as YAML or in a fenced \
code block. Instead, return a single JSON object that exactly matches the JSON Schema \
provided to the runtime via the --json-schema flag. \
\n\nFormat rules:\
\n- Return ONLY the JSON object — no preamble, no narration, no explanation, no fenced \
code blocks around the response itself.\
\n- The outer response must be a bare JSON object. Markdown values inside the JSON \
(e.g. a `description` field) MAY contain fenced code blocks like ```rust ...``` — only \
the outermost wrapping must be a bare object, not the string contents within it.\
\n- All required fields must be present. Do not invent additional fields not in the schema.";

/// Returns the system-prompt suffix to apply for the given response
/// format, or `None` when no override is needed (YAML path).
///
/// Call sites append this to the end of their system prompt before
/// dispatching, so the override always wins over earlier YAML
/// formatting instructions when [`ResponseFormat::JsonSchema`] is in
/// effect.
#[must_use]
pub fn response_format_system_suffix(format: ResponseFormat) -> Option<&'static str> {
    match format {
        ResponseFormat::Yaml => None,
        ResponseFormat::JsonSchema => Some(JSON_SCHEMA_RESPONSE_OVERRIDE),
    }
}

/// Appends [`response_format_system_suffix`] when needed.
///
/// Returns `prompt` with the suffix appended when the format is
/// [`ResponseFormat::JsonSchema`]; otherwise returns `prompt`
/// unchanged. Convenience for call sites that already have a system
/// prompt string in hand.
#[must_use]
pub fn apply_response_format_to_system_prompt(prompt: String, format: ResponseFormat) -> String {
    match response_format_system_suffix(format) {
        Some(suffix) => format!("{prompt}{suffix}"),
        None => prompt,
    }
}

#[cfg(test)]
mod response_format_tests {
    use super::*;

    #[test]
    fn yaml_format_returns_no_suffix() {
        assert!(response_format_system_suffix(ResponseFormat::Yaml).is_none());
    }

    #[test]
    fn json_schema_format_returns_override_suffix() {
        assert_eq!(
            response_format_system_suffix(ResponseFormat::JsonSchema),
            Some(JSON_SCHEMA_RESPONSE_OVERRIDE)
        );
    }

    #[test]
    fn apply_with_yaml_passes_prompt_through() {
        let original = "system prompt body".to_string();
        let result = apply_response_format_to_system_prompt(original.clone(), ResponseFormat::Yaml);
        assert_eq!(result, original);
    }

    #[test]
    fn apply_with_json_schema_appends_override() {
        let original = "system prompt body".to_string();
        let result =
            apply_response_format_to_system_prompt(original.clone(), ResponseFormat::JsonSchema);
        assert!(result.starts_with(&original));
        assert!(result.contains("STRUCTURED OUTPUT OVERRIDE"));
        assert!(result.len() > original.len());
    }

    /// The override addendum must explicitly carve out the embedded-fence
    /// case so PR descriptions containing rust/json/etc. fenced blocks
    /// inside the response's string fields are not mangled.
    #[test]
    fn override_carves_out_embedded_fences() {
        assert!(JSON_SCHEMA_RESPONSE_OVERRIDE.contains("Markdown values inside the JSON"));
    }

    /// Override must instruct the model to drop preamble/narration so a
    /// stray "Here is the response:" line doesn't trigger a re-prompt.
    #[test]
    fn override_forbids_preamble() {
        let lower = JSON_SCHEMA_RESPONSE_OVERRIDE.to_ascii_lowercase();
        assert!(
            lower.contains("no preamble") || lower.contains("only the json object"),
            "override should forbid preamble: {JSON_SCHEMA_RESPONSE_OVERRIDE}"
        );
    }
}

/// Default commit guidelines embedded from markdown file at compile time.
/// Used by both twiddle and check commands when no project-specific guidelines are provided.
const DEFAULT_COMMIT_GUIDELINES: &str = include_str!("../templates/default-commit-guidelines.md");

/// Basic system prompt for commit message improvement (Phase 1 & 2).
pub const BASIC_SYSTEM_PROMPT: &str = r#"You are an expert software engineer helping improve git commit messages. You will receive a YAML representation of a git repository with commit information and specific commit message guidelines to follow.

Your task is to analyze the commits and suggest improvements based on:
1. The actual code changes shown in the diff files
2. The commit message guidelines provided in the user prompt

CRITICAL: Your primary focus must be on the ACTUAL CODE CHANGES shown in the diff files. Base your commit messages on what the code actually does, not on file paths, branch names, or assumed context.

Analysis Rules:
1. **MOST IMPORTANT**: Read and analyze the diff_file content to understand what code changes were actually made
   - Look at lines with + (added) and - (removed) to see exactly what changed
   - Identify new functions, modified logic, added features, bug fixes, etc.
   - Focus on WHAT the code does, not WHERE it lives
2. Follow EXACTLY the commit message format and guidelines provided in the user prompt
3. Use imperative mood ("Add feature" not "Added feature") unless guidelines specify otherwise
4. Provide clear, concise descriptions of what the commit actually does (based on code changes)
5. Only suggest changes for commits that would benefit from improvement
6. Preserve the commit's original intent while improving clarity
7. Ignore generic file path patterns - focus on actual functionality changes

DIFF ANALYSIS EXAMPLES:
- Adding debug prints/logging = "debug: add debug logging for X" or "fix: improve error diagnostics for Y"
- Removing validation checks = "fix: allow empty X" or "refactor: remove unnecessary Y validation"  
- Changing error messages = "fix: improve error messages for Z"
- Adding new functionality = "feat: implement X capability"
- Bug fixes = "fix: resolve issue with Y"
- Adding detailed error output + removing validation = "fix: improve error handling and allow edge cases"

SPECIFIC EXAMPLE:
If diff shows:
+ eprintln!("DEBUG: YAML parsing failed...");
+ // Try to provide more helpful error messages
- if self.amendments.is_empty() { bail!("must contain at least one amendment"); }
+ // Empty amendments are allowed - they indicate no changes are needed

This should be: "fix(claude): improve YAML parsing diagnostics and allow empty amendments"
NOT: "feat(client): enhance context handling" (which ignores actual changes)

Analysis Priority:
1. First: What does the code change actually do? (from diff content)
2. Second: How can the message be improved for clarity and accuracy?
3. Third: Apply the exact format specification provided in the user prompt
4. Last: Are there any important implications or impacts to highlight?

TYPE SELECTION RULES (must match the commit checker's expectations):
1. Select the type from the NATURE of the change, not its description:
   - `docs` = ONLY when documentation files (.md, .txt, etc.) are the primary changes
   - `refactor` = code structure changed without behavior change (renaming, moving arguments, reorganizing)
   - `feat` = new user-facing functionality added
   - `fix` = bug or defect fixed
   - `test` = only test code changed
   - `ci` = only CI/CD pipeline files changed
   - `style` = only formatting/whitespace changed
   - `chore` = maintenance tasks, dependency updates
   - `build` = build system changes
   - `perf` = performance improvements
2. File-type constraints:
   - If only source code files (.rs, .py, .js, etc.) changed, NEVER use `docs`
   - If only test files changed, prefer `test`
   - If only CI/CD files changed, prefer `ci` — but use the detected_scope for more specific matches
   - Changing doc comments or help text in source code is `refactor` or `fix`, not `docs`
3. Before finalizing, verify: would the commit checker accept this type given the files that changed?

BREAKING CHANGE DETECTION (MANDATORY):
The commit checker enforces breaking-change markers at ERROR severity. You MUST detect breaking changes from the diff and emit BOTH markers when any of these signals appear:

DIFF SIGNALS — flag as a breaking change when the diff shows ANY of:
- A new MANDATORY parameter on a public function, public method, or pub trait method (no default, callers must update)
- A new MANDATORY field on a public struct/enum used in a public API, params type, request/response schema, or serialization format — INCLUDING adding a new `pub` field with no `#[serde(default)]` to an existing struct
- A removed, renamed, or re-typed public API (function, method, struct, enum variant, trait, type alias, public constant)
- A new required CLI flag/argument, or removal/rename of an existing one
- A change to an MCP tool schema that adds a new required parameter, removes a parameter, renames a parameter, makes an optional parameter required, or changes a parameter's type
- A change to a serialization format, file format, schema, or wire protocol that older readers cannot parse
- A default-behavior change that breaks non-interactive callers (e.g., a command that previously ran silently now prompts by default; a command that previously executed immediately now requires confirmation; a default value that callers depended on changed)
- A bumped MSRV, removed feature flag, or removed dependency that was part of the public API surface

ADDITIVE-LOOKING-BUT-BREAKING TRAP — Do NOT classify these as additive feat/fix:
- Adding a new field to an existing params/request/config struct WITHOUT `#[serde(default)]` or `Option<…>` — this breaks every existing caller that constructs the struct, because the field is now required. Example: adding `pub confirm: bool` to `WatcherRemoveParams` makes `WatcherRemoveParams { … }` literal calls fail to compile, and JSON callers that omit `confirm` get a deserialization error. THIS IS A BREAKING CHANGE.
- A subject like "add confirm guard" or "require confirm: true" describing a new mandatory gate is a strong textual signal that you are looking at a breaking change, even when the diff appears to "only add" code.
- Wrapping an existing default-on operation in a confirmation prompt or a guard that aborts unless an explicit flag is set IS a breaking change for non-interactive callers, even if the new flag/parameter is technically defaulted.

REQUIRED OUTPUTS — when ANY signal above is detected, the commit message MUST contain BOTH:
1. A `!` immediately after the type/scope and before the colon — e.g. `feat(cli)!: change output format` or `feat(api,cli)!: drop legacy flag`
2. A `BREAKING CHANGE:` footer (uppercase, exactly that label, followed by a colon) at the bottom of the body, separated from preceding paragraphs by a blank line, containing CONCRETE migration instructions — what callers must do, not just that something broke

WRONG: `feat(cli): change output format` (missing `!` and footer despite removed flag)
WRONG: `feat(cli)!: change output format` (has `!` but no `BREAKING CHANGE:` footer)
WRONG: `feat(cli)!: change output format\n\nBREAKING CHANGE: output format changed` (footer is vacuous; no migration guidance)
WRONG: `feat(mcp): add confirm guard to destructive remove tools` (adds mandatory `confirm: bool` parameter to existing MCP tool params — IS a breaking change, missing both `!` and footer)
RIGHT: `feat(cli)!: drop --legacy-output flag\n\nBREAKING CHANGE: the --legacy-output flag has been removed. Callers should pass --format=json instead; the JSON shape is documented in docs/output-format.md.`
RIGHT: `feat(mcp)!: require confirm: true for destructive remove tools\n\nBREAKING CHANGE: jira_watcher_remove, jira_link_remove, and confluence_label_remove now require a mandatory confirm: bool parameter. Callers that omit confirm or pass confirm: false receive an error. Update all callers to include "confirm": true to preserve current behaviour.`

If the diff contains NONE of the signals above, do NOT emit `!` or a `BREAKING CHANGE:` footer — these markers are reserved for actual breaking changes and devalue when applied to non-breaking commits.

CRITICAL OUTPUT REQUIREMENT: Return exactly one amendment per commit in the input `commits[]` array — no more, no fewer. Count the entries in `commits[]` and produce that many amendments. Each amendment's `commit` field must match a hash that appears in the input. DO NOT invent additional amendments, duplicate a commit hash across multiple amendments, or omit any input commit. If a commit message is already perfect, include it unchanged with its original hash.

CRITICAL RESPONSE FORMAT: You MUST respond with ONLY valid YAML content. Do not include any explanatory text, markdown wrappers, or code blocks. Your entire response must be parseable YAML starting immediately with "amendments:" and containing nothing else.

Your response must follow this exact YAML structure:

amendments:
  - commit: "full-40-character-sha1-hash"
    message: "improved commit message"
    summary: "One sentence describing what this commit changes"
  - commit: "another-full-40-character-sha1-hash"
    message: "another improved commit message"
    summary: "One sentence describing what this commit changes"

DO NOT include:
- Any explanatory text before the YAML
- Markdown code blocks (```)
- Commentary or analysis
- Any text after the YAML
- Any non-YAML content whatsoever

Your response must start with "amendments:" and be valid YAML only.

CRITICAL YAML FORMATTING REQUIREMENTS:
1. For single-line messages: Use quoted strings ("message here")
2. For multi-line messages: Use literal block scalar (|) format like this:
   message: |
     subject line here
     
     Body paragraph here with details.
     
     - Bullet point 1
     - Bullet point 2
     - Bullet point 3
     
     Additional paragraphs as needed.

3. NEVER put bullet points or multiple sentences on the same line
4. Use proper indentation and line breaks for readability
5. Leave blank lines between sections for better formatting"#;

/// Legacy alias for backward compatibility.
pub const SYSTEM_PROMPT: &str = BASIC_SYSTEM_PROMPT;

/// Generates a contextual system prompt based on project and commit context (Phase 3).
///
/// # Note
///
/// This is a convenience wrapper that hardcodes [`PromptStyle::Claude`].
/// Use [`generate_contextual_system_prompt_for_provider`] when the active provider is
/// known at the call site (i.e. via [`crate::claude::ai::AiClientMetadata::prompt_style`]).
pub fn generate_contextual_system_prompt(context: &CommitContext) -> String {
    generate_contextual_system_prompt_for_provider(context, PromptStyle::Claude)
}

/// Generates a contextual system prompt with provider-specific handling.
///
/// Provider-specific behaviour is limited to the commit-guidelines section:
/// - [`PromptStyle::Claude`]: frames guidelines as a literal template to reproduce exactly.
/// - [`PromptStyle::OpenAi`]: frames guidelines as guidance to follow, with explicit
///   bullet-point instructions to avoid copying the guideline text verbatim.
///
/// The base prompt (`BASIC_SYSTEM_PROMPT`), verbosity hints, branch context, work-pattern
/// context, and scope-consistency guidance are identical across providers.  Check prompts,
/// coherence prompts, and user prompts are not provider-specific because the observed
/// behavioural difference (template-reproduction vs. guidance-interpretation) only manifests
/// when the guidelines section is present.
pub fn generate_contextual_system_prompt_for_provider(
    context: &CommitContext,
    provider: PromptStyle,
) -> String {
    let mut prompt = BASIC_SYSTEM_PROMPT.to_string();

    // CRITICAL: Emphasize diff analysis priority even with context
    prompt.push_str("\n\n=== CONTEXTUAL INTELLIGENCE GUIDELINES ===");
    prompt.push_str(
        "\nWhile this system has access to project context, branch analysis, and work patterns,",
    );
    prompt.push_str("\nyou MUST still prioritize the actual code changes over contextual hints.");
    prompt.push('\n');
    prompt.push_str("\nContext Usage Priority:");
    prompt.push_str("\n1. PRIMARY: Analyze diff content - what does the code actually do?");
    prompt.push_str(
        "\n2. SECONDARY: Use project context for scope selection and formatting preferences",
    );
    prompt.push_str(
        "\n3. TERTIARY: Use branch context for additional clarity, not as primary message source",
    );
    prompt.push('\n');
    prompt.push_str("\nDO NOT generate commit messages based solely on:");
    prompt.push_str("\n- File paths or directory names");
    prompt.push_str("\n- Branch naming patterns");
    prompt.push_str("\n- Assumed project context");
    prompt.push('\n');
    prompt.push_str("\nALWAYS base messages on what the code changes actually accomplish.");

    // Add verbosity guidance based on change significance
    match context.suggested_verbosity() {
        VerbosityLevel::Comprehensive => {
            prompt.push_str(
                "\n\nFor significant changes, provide comprehensive commit messages with:",
            );
            prompt.push_str("\n- Detailed subject line describing the enhancement");
            prompt.push_str("\n- Multi-paragraph body explaining what was added/changed");
            prompt.push_str("\n- Bulleted lists for complex additions");
            prompt.push_str("\n- Impact statement explaining the significance");
        }
        VerbosityLevel::Detailed => {
            prompt.push_str("\n\nFor moderate changes, provide detailed commit messages with:");
            prompt.push_str("\n- Clear subject line with specific scope");
            prompt.push_str("\n- Multi-paragraph body explaining the change and its purpose");
            prompt.push_str("\n- Bulleted lists for key improvements or additions");
            prompt.push_str("\n- Explain the impact and value of the changes");
        }
        VerbosityLevel::Concise => {
            prompt.push_str("\n\nFor minor changes, focus on clear, concise commit messages.");
        }
    }

    // Add project-specific commit guidelines with provider-specific handling
    if let Some(guidelines) = &context.project.commit_guidelines {
        if provider == PromptStyle::Claude {
            // Claude models handle "literal template" instructions correctly
            prompt.push_str("\n\n=== MANDATORY COMMIT MESSAGE TEMPLATE ===");
            prompt.push_str("\nThis is a LITERAL TEMPLATE that you must reproduce EXACTLY.");
            prompt.push_str("\nDo NOT treat this as guidance - it is a FORMAT SPECIFICATION.");
            prompt.push_str("\nEvery character, marker, and structure element must be preserved:");
            prompt.push_str(&format!("\n\n{guidelines}"));
            prompt.push_str("\n\nCRITICAL TEMPLATE REPRODUCTION RULES:");
            prompt.push_str(
                "\n1. This is NOT a description of how to write commits - it IS the actual format",
            );
            prompt.push_str(
                "\n2. Every element shown above must appear in your commit messages exactly as shown",
            );
            prompt.push_str(
                "\n3. Any text, markers, or symbols in the template are LITERAL and must be included",
            );
            prompt.push_str(
                "\n4. The structure, spacing, and all content must be reproduced verbatim",
            );
            prompt.push_str(
                "\n5. Replace only obvious placeholders like <type>, <scope>, <description>",
            );
            prompt.push_str(
                "\n6. Everything else in the template is literal text that must appear in every commit",
            );
            prompt.push_str(
                "\n\nWRONG: Treating the above as 'guidance' and writing conventional commits",
            );
            prompt.push_str(
                "\nRIGHT: Using the above as a literal template and reproducing its exact structure",
            );
        } else {
            // OpenAI and other models need clearer guidance-based instructions
            prompt.push_str("\n\n=== PROJECT COMMIT GUIDELINES ===");
            prompt.push_str("\nThis project has specific commit guidelines that you MUST follow when improving commit messages.");
            prompt.push_str("\nThese are GUIDELINES for how to write commits, not text to copy:");
            prompt.push_str(&format!("\n\n{guidelines}"));
            prompt.push_str("\n\nCRITICAL GUIDELINES USAGE:");
            prompt.push_str(
                "\n1. These are GUIDELINES that describe how to write commit messages for this project",
            );
            prompt.push_str(
                "\n2. Follow the format, style, and conventions described in the guidelines",
            );
            prompt.push_str("\n3. Use the specified commit types, scopes, and formatting rules");
            prompt.push_str("\n4. Write proper commit messages that follow these guidelines");
            prompt.push_str("\n5. Do NOT copy the guidelines text itself into commit messages");
            prompt.push_str(
                "\n6. Create commit messages that would be approved according to these guidelines",
            );
            prompt.push_str("\n\nWRONG: Copying the guidelines document into the commit message");
            prompt.push_str(
                "\nRIGHT: Writing commit messages that follow the guidelines' format and rules",
            );
        }
    }

    // Add valid scopes if available
    if !context.project.valid_scopes.is_empty() {
        let scopes = context
            .project
            .valid_scopes
            .iter()
            .map(|s| format!("- {}: {}", s.name, s.description))
            .collect::<Vec<_>>()
            .join("\n");
        prompt.push_str(&format!("\n\nValid scopes for this project:\n{scopes}"));
    }

    // Add branch context
    if context.branch.is_feature_branch {
        prompt.push_str(&format!(
            "\n\nBranch context: This is {} on '{}'. Consider this context when improving commit messages.",
            context.branch.work_type,
            context.branch.description
        ));
    }

    // Add work pattern context
    match context.range.work_pattern {
        WorkPattern::Sequential => {
            prompt.push_str("\n\nWork pattern: Sequential feature development. Ensure commit messages show logical progression and build upon each other.");
        }
        WorkPattern::Refactoring => {
            prompt.push_str("\n\nWork pattern: Refactoring work. Focus on clarity about what's being restructured and why. Emphasize improvements in code quality or architecture.");
        }
        WorkPattern::BugHunt => {
            prompt.push_str("\n\nWork pattern: Bug investigation and fixes. Emphasize the problem being solved and the solution approach.");
        }
        WorkPattern::Documentation => {
            prompt.push_str("\n\nWork pattern: Documentation updates. Focus on what documentation was added/improved and its value to users or developers.");
        }
        WorkPattern::Configuration => {
            prompt.push_str("\n\nWork pattern: Configuration changes. Explain what settings were modified and their impact on functionality.");
        }
        WorkPattern::Unknown => {
            // No additional context
        }
    }

    // Add scope consistency guidance
    if let Some(consistent_scope) = &context.range.scope_consistency.consistent_scope {
        if context.range.scope_consistency.confidence > 0.7 {
            prompt.push_str(&format!(
                "\n\nScope consistency: Most changes appear to be in the '{consistent_scope}' scope. Consider using this scope consistently unless files clearly belong to different areas."
            ));
        }
    }

    prompt
}

/// Generates a basic user prompt from repository view YAML (Phase 1 & 2).
pub fn generate_user_prompt(repo_yaml: &str) -> String {
    format!(
        r"Please analyze the following repository information and suggest commit message improvements:

{repo_yaml}

CRITICAL ANALYSIS STEPS:
1. **READ THE DIFF FILES**: For each commit, carefully read the diff_file content to understand exactly what code changes were made
2. **IDENTIFY ACTUAL FUNCTIONALITY**: Determine what the code changes actually accomplish, not what file paths suggest
3. **CHOOSE APPROPRIATE TYPE**: Select commit type (feat/fix/refactor/etc.) based on actual changes, not file locations
4. **SELECT MEANINGFUL SCOPE**: Choose scope based on functionality affected, not just directory names

MANDATORY CARDINALITY: The repository data above contains a `commits[]` array. Return exactly one amendment per entry — no more, no fewer. Each amendment's `commit` field must be a hash that appears in `commits[]`. Do not invent additional commits, do not emit two amendments with the same hash, and do not skip any input commit.

For each commit, analyze whether improvements are needed:
- Check if it follows conventional commit format
- Verify descriptions accurately reflect the actual code changes
- Ensure imperative mood is used (not past tense)
- Confirm verbosity matches the scope of changes made
- Validate type/scope classification based on real functionality
- Ensure messages describe what the code actually does (not generic descriptions)

Remember: File paths and directory names are just hints. The diff content shows the real changes.

CRITICAL: Even if a commit message is perfect and needs no changes, include it in the amendments array with its current message and original hash. Do not skip any commit, and do not emit more amendments than there are commits in the input.

SUMMARY FIELD: For each commit, include a `summary` field containing one sentence describing what the commit changes. Keep it factual and brief.{BREAKING_CHANGE_FINAL_PASS}"
    )
}

/// Generates a contextual user prompt with enhanced analysis (Phase 3).
pub fn generate_contextual_user_prompt(repo_yaml: &str, context: &CommitContext) -> String {
    let mut prompt = format!(
        "Please analyze the following repository information and suggest commit message improvements:\n\n{repo_yaml}\n\n"
    );

    // Commit guidelines are now handled in the system prompt for maximum authority
    // Only show default guidelines if no project-specific ones exist
    if context.project.commit_guidelines.is_none() {
        prompt.push_str("=== COMMIT GUIDELINES ===\n");
        prompt.push_str("Follow these commit guidelines:\n\n");
        prompt.push_str(DEFAULT_COMMIT_GUIDELINES);
        prompt.push_str("\n\n");
    }

    // Emphasize diff analysis even with contextual intelligence
    prompt.push_str("CRITICAL ANALYSIS STEPS (WITH CONTEXT):\n");
    prompt.push_str(
        "1. **READ THE DIFF FILES FIRST**: Understand exactly what code changes were made\n",
    );
    prompt.push_str("2. **IDENTIFY ACTUAL FUNCTIONALITY**: What does the code actually do?\n");
    prompt.push_str("3. **APPLY CONTEXTUAL INTELLIGENCE**: Use project context to enhance accuracy, not replace analysis\n");
    prompt.push_str(
        "4. **SELECT TYPE & SCOPE**: Based on actual changes + project scope definitions\n",
    );
    prompt.push('\n');

    // Add context-specific focus areas
    prompt.push_str("MANDATORY CARDINALITY: The repository data above contains a `commits[]` array. Return exactly one amendment per entry — no more, no fewer. Each amendment's `commit` field must be a hash that appears in `commits[]`. Do not invent additional commits, do not emit two amendments with the same hash, and do not skip any input commit.\n\n");
    prompt.push_str("For each commit, analyze whether improvements are needed:\n");
    prompt.push_str("- Check if it follows conventional commit format\n");
    prompt.push_str("- Verify descriptions are clear and accurate\n");
    prompt.push_str("- Ensure imperative mood is used (not past tense)\n");

    // Add significance-based criteria
    if context.is_significant_change() {
        prompt.push_str("- Lack sufficient detail for significant changes\n");
        prompt.push_str("- Don't explain the impact or rationale for major modifications\n");
        prompt.push_str("- Miss opportunities to highlight important architectural changes\n");
    } else {
        prompt.push_str("- Are too verbose for simple changes\n");
        prompt.push_str("- Could be more concise while remaining clear\n");
    }

    // Add project-specific focus
    if !context.project.valid_scopes.is_empty() {
        prompt.push_str("- Use incorrect or missing scopes based on file changes\n");
    }

    // Add work pattern specific guidance
    match context.range.work_pattern {
        WorkPattern::Refactoring => {
            prompt.push_str("- Don't clearly explain what was refactored and why\n");
        }
        WorkPattern::Documentation => {
            prompt.push_str("- Don't specify what documentation was improved or added\n");
        }
        WorkPattern::BugHunt => {
            prompt.push_str("- Don't clearly describe the problem being fixed\n");
        }
        _ => {}
    }

    prompt.push_str("\nWhen creating improved messages:\n");

    match context.suggested_verbosity() {
        VerbosityLevel::Comprehensive => {
            prompt.push_str("- Provide comprehensive multi-paragraph commit messages\n");
            prompt.push_str("- Include detailed explanations of changes and their impact\n");
            prompt.push_str("- Use bulleted lists for complex additions\n");
            prompt.push_str("- Add impact statements for significant changes\n");
        }
        VerbosityLevel::Detailed => {
            prompt.push_str("- Provide clear subject lines with detailed explanatory body\n");
            prompt.push_str(
                "- Use multi-paragraph descriptions explaining the changes and their purpose\n",
            );
            prompt.push_str("- Include bulleted lists for key improvements or additions\n");
            prompt.push_str("- Explain the impact and value to users or developers\n");
        }
        VerbosityLevel::Concise => {
            prompt.push_str("- Keep messages concise but descriptive\n");
            prompt.push_str("- Focus on clear, single-line conventional commit format\n");
        }
    }

    prompt.push_str("\nCRITICAL: Return exactly one amendment per input commit. Even if a commit message is perfect, include it with its current message and original hash. Do not skip any commit, and do not emit more amendments than there are commits in the input.");
    prompt.push_str(SUMMARY_INSTRUCTION);
    prompt.push_str(BREAKING_CHANGE_FINAL_PASS);

    prompt
}

/// Final-pass nudge appended to user prompts so the breaking-change rule is the
/// last thing the model reads before emitting YAML. Mirrors the system-prompt
/// `BREAKING CHANGE DETECTION` block but at the user-prompt level for recency
/// bias — empirical fix for #744 where a system-prompt-only rule was ignored.
const BREAKING_CHANGE_FINAL_PASS: &str = "\n\nFINAL BREAKING-CHANGE PASS (DO THIS LAST, BEFORE EMITTING YAML):\nFor each amendment you are about to emit, re-scan the diff for the breaking-change signals listed in the system prompt — especially: new required parameters/fields on existing public APIs or MCP tool params, removed/renamed public APIs, removed/renamed CLI flags, default-behavior changes that break non-interactive callers (e.g., new confirmation prompts on previously-unattended commands). If ANY signal is present, the amendment's message MUST contain BOTH `!` after the type/scope AND a `BREAKING CHANGE:` footer with concrete migration instructions. If a subject says things like \"add confirm guard\", \"require X\", \"now prompts by default\", or \"add mandatory <field>\" without a `!` and footer, you have made a mistake — fix it before emitting.";

/// System prompt for PR description generation.
pub const PR_GENERATION_SYSTEM_PROMPT: &str = r#"You are a software engineer generating pull request descriptions. You will receive git repository data and a PR template.

Your task:
1. Analyze the code changes in the diff files
2. Fill out the PR template with specific information about what was changed
3. Replace template placeholders with actual details

Analysis steps:
1. Read the diff files to understand what code was changed
2. Determine if this is a new feature, bug fix, or other type of change
3. Fill in the template with accurate information about the changes

RESPONSE FORMAT: Respond with YAML only. No explanations or markdown blocks.

Structure:
title: "Short descriptive title"
description: |
  Filled-in template content here

Requirements:
- Replace all template placeholders with real information
- Check appropriate boxes based on actual changes
- Remove template comments and instructions
- Provide specific details about what was changed"#;

/// Generates a PR description using AI analysis.
pub fn generate_pr_description_prompt(repo_yaml: &str, pr_template: &str) -> String {
    format!(
        r#"Please analyze the following repository information and generate a comprehensive pull request description by filling in the provided template:

Repository Information:
{repo_yaml}

PR Template to Fill:
{pr_template}

INSTRUCTIONS:
1. **ANALYZE THE COMMITS AND DIFFS**: Read through all commits and their diff files to understand exactly what changes were made
2. **UNDERSTAND THE OVERALL PURPOSE**: Determine what this branch accomplishes as a whole
3. **FILL THE TEMPLATE**: Replace placeholder text with specific, accurate information based on your analysis
4. **CHECK APPROPRIATE BOXES**: Mark the correct type of change checkboxes based on actual changes
5. **BE SPECIFIC**: Provide concrete details about what was added, changed, or fixed
6. **EXPLAIN VALUE**: Describe why these changes are beneficial or necessary
7. **LIST CHANGES**: Provide specific bullet points of what was modified
8. **INCLUDE CONTEXT**: Add any relevant background or rationale for the changes

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

title: "Your concise PR title here"
description: |
  Your filled-in PR template in markdown format here.

Start immediately with "title:" and provide only YAML content. Ensure the title is concise (50-80 characters) and the description contains the complete filled-in template."#
    )
}

/// Generates a PR system prompt with project context and guidelines.
///
/// # Note
///
/// This is a convenience wrapper that hardcodes [`PromptStyle::Claude`].
/// Use [`generate_pr_system_prompt_with_context_for_provider`] when the active provider is
/// known at the call site (i.e. via [`crate::claude::ai::AiClientMetadata::prompt_style`]).
pub fn generate_pr_system_prompt_with_context(
    context: &crate::data::context::CommitContext,
) -> String {
    generate_pr_system_prompt_with_context_for_provider(context, PromptStyle::Claude)
}

/// Generates a PR system prompt with provider-specific handling.
///
/// Provider-specific behaviour applies to the template-filling instructions:
/// - [`PromptStyle::Claude`]: brief reminder that the PR template is to be filled out,
///   not copied — Claude handles this correctly with minimal instruction.
/// - [`PromptStyle::OpenAi`]: explicit bullet-point instructions with a concrete example
///   of what "fill out" means, because OpenAI models need more explicit guidance to avoid
///   reproducing placeholder text verbatim.
pub fn generate_pr_system_prompt_with_context_for_provider(
    context: &crate::data::context::CommitContext,
    provider: PromptStyle,
) -> String {
    let mut prompt = PR_GENERATION_SYSTEM_PROMPT.to_string();

    // Add provider-specific template handling instructions
    if provider == PromptStyle::Claude {
        prompt.push_str("\n\n=== TEMPLATE HANDLING FOR CLAUDE ===");
        prompt.push_str(
            "\nThe PR template provided is a TEMPLATE TO FILL OUT, not literal text to copy.",
        );
        prompt.push_str(
            "\nYou must REPLACE placeholder content with actual information about the changes.",
        );
    } else {
        prompt.push_str("\n\n=== TEMPLATE FILLING INSTRUCTIONS ===");
        prompt.push_str("\nThe provided PR template should be filled out with specific information about the changes.");
        prompt.push_str("\nReplace placeholder content with actual details:");
        prompt.push_str("\n- Fill in the Description section with what this PR actually does");
        prompt.push_str("\n- Mark the correct Type of Change checkboxes");
        prompt.push_str("\n- List the specific changes made in the Changes Made section");
        prompt.push_str("\n- Remove placeholder text like '(issue_number)' and template comments");
        prompt.push_str("\n- Replace empty bullet points with actual information");
        prompt.push_str("\n\nExample: Instead of '**Core Changes:**\\n-\\n-', write '**Core Changes:**\\n- Added OpenAI API client\\n- Implemented provider-specific prompts'");
    }

    // Add project-specific PR guidelines if available
    if let Some(pr_guidelines) = &context.project.pr_guidelines {
        prompt.push_str("\n\n=== PROJECT PR GUIDELINES ===");
        prompt.push_str("\nThis project has specific guidelines for pull request descriptions:");
        prompt.push_str(&format!("\n\n{pr_guidelines}"));
        prompt.push_str("\n\nIMPORTANT: Follow these project-specific guidelines when generating the PR description.");
        prompt.push_str("\nUse these guidelines to inform the style, level of detail, and specific sections to emphasize.");
    }

    // Add scope information if available
    if !context.project.valid_scopes.is_empty() {
        let scope_names: Vec<&str> = context
            .project
            .valid_scopes
            .iter()
            .map(|s| s.name.as_str())
            .collect();
        prompt.push_str(&format!(
            "\n\nValid scopes for this project: {}",
            scope_names.join(", ")
        ));
    }

    prompt
}

/// Generates a PR description prompt with project context.
pub fn generate_pr_description_prompt_with_context(
    repo_yaml: &str,
    pr_template: &str,
    context: &crate::data::context::CommitContext,
) -> String {
    let mut prompt = format!(
        r"Please analyze the following repository information and generate a comprehensive pull request description following the project's specific guidelines:

Repository Information:
{repo_yaml}

PR Template:
{pr_template}

"
    );

    // Add project context information
    if context.project.pr_guidelines.is_some() {
        prompt
            .push_str("IMPORTANT: This project has specific PR guidelines that must be followed. ");
        prompt.push_str("Review the guidelines in the system prompt and apply them to create an appropriate PR description.\n\n");
    }

    // Add branch context if available
    if context.branch.is_feature_branch {
        prompt.push_str(&format!(
            "BRANCH CONTEXT: This is {} work on '{}'. Use this context to better describe the purpose and scope.\n\n",
            context.branch.work_type, context.branch.description
        ));
    }

    prompt.push_str(r#"INSTRUCTIONS:
1. **ANALYZE THE COMMITS AND DIFFS**: Read through all commits and their diff files to understand exactly what changes were made
2. **UNDERSTAND THE OVERALL PURPOSE**: Determine what this branch accomplishes as a whole
3. **FOLLOW PROJECT GUIDELINES**: Apply any project-specific PR guidelines provided in the system prompt
4. **GENERATE COMPREHENSIVE DESCRIPTION**: Create a clear, informative PR description that explains the changes
5. **USE APPROPRIATE DETAIL LEVEL**: Match the level of detail to the significance of the changes
6. **BE SPECIFIC**: Provide concrete details about what was added, changed, or fixed based on actual code changes
7. **EXPLAIN VALUE**: Describe why these changes are beneficial or necessary
8. **REPLACE PLACEHOLDERS**: Remove all placeholder text, comments, and generic content
9. **INCLUDE ACTUAL CHANGES**: List specific bullet points of what was modified based on the diffs

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

title: "Your concise PR title here"
description: |
  Your comprehensive PR description in markdown format here.
  Follow project guidelines and replace all template placeholders with actual information.

Start immediately with "title:" and provide only YAML content. The title should follow conventional commit format when appropriate and the description should be tailored to this project's standards."#);

    prompt
}

/// System prompt for commit message check/validation.
pub const CHECK_SYSTEM_PROMPT: &str = r#"You are a commit message reviewer. Your task is to evaluate commit messages against project guidelines and report violations.

You will receive:
1. Project commit guidelines (with severity annotations in a "Severity Levels" section)
2. Commit information including the message and diff

## Severity Levels

The guidelines contain a "Severity Levels" section with a table mapping sections to severities:

```markdown
## Severity Levels

| Severity | Sections                       |
|----------|--------------------------------|
| error    | Format, Subject Line, Accuracy |
| warning  | Content                        |
| info     | Style                          |
```

Meaning:
- `error` = Violations that block CI (exit code 1)
- `warning` = Advisory issues (exit code 0, or 2 with --strict)
- `info` = Suggestions only (never affect exit code)

Sections not listed in the severity table default to `warning`.

## Your Task

For each commit:
1. Check if the message follows each guideline section
2. Compare the message against the actual diff to verify accuracy
3. Report violations with the severity from that section's annotation
4. Suggest a corrected message if there are issues

## Accuracy Checks (Critical)

These are the core value-add checks - compare what the message *claims* against what the diff *shows*:
- Does the commit type match the actual changes? (e.g., don't use `feat` for a bug fix)
- Does the scope match files modified?
- Does the description accurately reflect what was done?
- Are important changes mentioned? (e.g., rate limiting, breaking changes)

## Response Format

CRITICAL: Respond with ONLY valid YAML content. Do not include any explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

checks:
  - commit: "abc123..."
    passes: false
    issues:
      - reasoning: "Subject 'Added user endpoint' begins with 'Added', a past-tense verb. The Subject Line section requires imperative mood ('add', not 'added'/'adds'). Section 'Subject Line' maps to severity 'error'."
        severity: error
        section: "Subject Line"
        rule: "Use imperative mood"
        explanation: "Subject uses past tense ('Added'); should use imperative ('add')"
      - reasoning: "Diff shows 142 lines changed. Body Guidelines requires a body for large changes. No body present. Section 'Content' maps to severity 'warning'."
        severity: warning
        section: "Body Guidelines"
        rule: "Body required for large changes"
        explanation: "142 lines changed but no body provided"
    suggestion:
      message: |
        feat(api): add user endpoint

        Implement POST /api/users with validation.
      explanation: |
        - Changed subject to imperative mood
        - Added body explaining the change
    summary: "Add REST endpoint for user creation with input validation"

For commits that pass all checks:
  - commit: "def456..."
    passes: true
    issues: []
    summary: "Update CI pipeline to run tests in parallel"

CRITICAL — REASONING MUST PRECEDE VERDICT:
Every issue entry MUST begin with a `reasoning` field, written BEFORE the `severity` field, in the exact field order shown above. The `reasoning` field is where you work out whether the rule is actually violated. Walk through the evidence: what the message says, what the diff or valid-scopes list shows, and whether pre_validated_checks covers it. Only after the reasoning concludes do you commit to a `severity` value.

Do NOT write the severity first and then justify it. Do NOT emit an issue whose `reasoning` concludes the message is valid — if your reasoning finds no violation, omit the issue entirely (or report it at severity `info` if it's merely a style suggestion). The `reasoning` and `severity` fields must be self-consistent; a contradictory issue (e.g., reasoning says "this is valid" but severity is `error`) is a bug in your output.

IMPORTANT:
- Include ALL commits in the response, whether they pass or fail
- Use the exact severity from the guidelines' severity table
- Set `passes: true` only if there are no error or warning level issues
- Info-level issues do not affect the `passes` status

## Pre-validated Checks

Some commits include a `pre_validated_checks` field containing deterministic checks already performed. These are AUTHORITATIVE — do not contradict them. For example, if pre_validated_checks says "Scope validity verified: 'cli' is in the valid scopes list", do NOT report an error saying the scope is invalid."#;

/// Generates a check system prompt with project guidelines.
pub fn generate_check_system_prompt(guidelines: Option<&str>) -> String {
    generate_check_system_prompt_with_scopes(guidelines, &[])
}

/// Generates a check system prompt with project guidelines and valid scopes.
pub fn generate_check_system_prompt_with_scopes(
    guidelines: Option<&str>,
    valid_scopes: &[crate::data::context::ScopeDefinition],
) -> String {
    let mut prompt = CHECK_SYSTEM_PROMPT.to_string();

    prompt.push_str("\n\n=== PROJECT COMMIT GUIDELINES ===\n");
    prompt.push_str("Evaluate commits against these guidelines:\n\n");

    if let Some(project_guidelines) = guidelines {
        prompt.push_str(project_guidelines);
    } else {
        prompt.push_str(DEFAULT_COMMIT_GUIDELINES);
    }

    // Add valid scopes if available (ensures check uses same scopes as twiddle)
    if !valid_scopes.is_empty() {
        prompt.push_str("\n\n=== VALID SCOPES FOR THIS PROJECT ===\n");
        prompt.push_str("The following scopes are valid for this project:\n\n");
        for scope in valid_scopes {
            prompt.push_str(&format!("- `{}`: {}\n", scope.name, scope.description));
        }
        prompt.push_str(concat!(
            "\n## Scope Checking Rules\n\n",
            "There are TWO distinct scope checks with different severities:\n\n",
            "1. **Scope Validity** (severity: error, section: \"Accuracy\"): ",
            "The scope is NOT in the valid scopes list above. ",
            "Only report this if pre_validated_checks does NOT confirm the scope is valid.\n\n",
            "2. **Scope Appropriateness** (severity: info, section: \"Scope Appropriateness\"): ",
            "The scope IS in the valid list, but a different valid scope might better match ",
            "the changed files. This is a suggestion only — never an error.\n\n",
            "IMPORTANT: If pre_validated_checks says the scope is valid, you MUST NOT ",
            "report it as an Accuracy error. You may suggest a more appropriate scope at info level.",
        ));
    }

    prompt.push_str("\n\nCRITICAL: Use the Severity Levels table above to determine the severity of each violation. If a section is not listed, default to 'warning'.");

    prompt
}

/// Summary field instruction appended to amendment and check prompts.
const SUMMARY_INSTRUCTION: &str = "\n\nSUMMARY FIELD: For each commit, include a `summary` field containing one sentence describing what the commit changes. This is used for cross-commit coherence analysis. Keep it factual and brief — no diff details, just the functional intent.";

/// Generates a user prompt for the check command.
pub fn generate_check_user_prompt(repo_yaml: &str, include_suggestions: bool) -> String {
    let mut prompt = format!(
        r"Please analyze the following commits and check their messages against the guidelines:

{repo_yaml}

ANALYSIS STEPS:
1. For each commit, read the diff content to understand what was actually changed
2. Compare the commit message against each guideline section
3. Report any violations with appropriate severity level from the guidelines
4. Check accuracy: does the message accurately describe the actual code changes?

"
    );

    if include_suggestions {
        prompt.push_str("SUGGESTIONS: For commits with issues, provide a corrected message suggestion with explanation of improvements.\n\n");
    } else {
        prompt.push_str("SUGGESTIONS: Do NOT include suggestion fields - only report issues.\n\n");
    }

    prompt.push_str(r#"MANDATORY: Include ALL commits in the checks array, whether they pass or fail.

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content starting with "checks:". Do not include any explanatory text, markdown wrappers, or code blocks."#);

    prompt.push_str(SUMMARY_INSTRUCTION);

    prompt
}

/// System prompt for the amendment coherence pass.
///
/// Reviews individually-generated amendments for cross-commit consistency,
/// normalizing scopes, detecting rename chains, and removing redundancy.
pub const AMENDMENT_COHERENCE_SYSTEM_PROMPT: &str = r#"You are an expert software engineer reviewing a set of proposed commit message amendments for cross-commit coherence.

Each commit was analyzed individually. You now see all the proposed messages and summaries together. Your task is to refine the messages for consistency across the entire set.

Review for:
1. **Scope normalization**: If related commits use different scopes for the same area, standardize them
2. **Rename chains**: If commit A renames X→Y and commit B updates references to Y, note the relationship
3. **Redundant descriptions**: Differentiate commits with similar descriptions (e.g., multiple "update dependencies")
4. **Consistent terminology**: Use the same terms for the same concepts across commits
5. **Logical grouping**: Ensure related commits have messages that reflect their relationship

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

amendments:
  - commit: "full-40-character-sha1-hash"
    message: |
      type(scope): subject line

      Body paragraph preserved from input.
  - commit: "another-full-40-character-sha1-hash"
    message: "single-line message if input had no body"

IMPORTANT:
- Include ALL commits from the input, even those that need no refinement
- Preserve the original commit hashes exactly
- Only change messages where cross-commit coherence improvements are needed
- Keep changes minimal — do not rewrite messages that are already good
- PRESERVE MESSAGE BODIES: If a message has a multi-line body (subject + blank line + paragraphs), keep the body intact. Only refine the subject line or body wording where cross-commit coherence requires it. Do not strip bodies down to single-line messages.
- Use YAML literal block scalar (|) for multi-line messages
- Your response must start with "amendments:" and be valid YAML only"#;

/// System prompt for the check coherence pass.
///
/// Reviews individually-generated check results for cross-commit consistency.
pub const CHECK_COHERENCE_SYSTEM_PROMPT: &str = r#"You are an expert commit message reviewer examining check results that were generated for individual commits. You now see all results together and should refine them for cross-commit coherence.

Review for:
1. **Scope consistency**: Flag if related commits use inconsistent scopes
2. **Cross-commit accuracy**: Detect if commit messages reference changes in other commits incorrectly
3. **Consistent severity**: Ensure similar issues get the same severity across commits
4. **Missing cross-commit issues**: Flag coordination problems only visible when viewing all commits together

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

checks:
  - commit: "abc123..."
    passes: true/false
    issues:
      - reasoning: "Cross-commit analysis of why this is (or is not) an issue. Work through the evidence before committing to severity."
        severity: error/warning/info
        section: "Section Name"
        rule: "Rule description"
        explanation: "Why this is an issue"
    suggestion:
      message: |
        refined commit message
      explanation: |
        - Reason for refinement

CRITICAL — REASONING MUST PRECEDE VERDICT:
Every issue entry MUST begin with a `reasoning` field, written BEFORE the `severity` field, in the exact field order shown above. Work through the evidence in `reasoning` first, then commit to `severity`. If your reasoning concludes the finding is valid (not a violation), omit the issue or downgrade to `info`. The `reasoning` and `severity` fields must be self-consistent.

IMPORTANT:
- Include ALL commits from the input
- Preserve original issues — only add cross-commit issues or adjust severity for consistency
- Set `passes: true` only if there are no error or warning level issues
- Your response must start with "checks:" and be valid YAML only"#;

/// System prompt for merging partial chunk amendments into a single commit message.
///
/// When a commit's diff is too large for one AI request, it is split into
/// file-level chunks and each chunk produces a partial amendment. This prompt
/// drives a reduce pass that synthesizes those partial amendments into one
/// cohesive message.
pub(crate) const AMENDMENT_CHUNK_MERGE_SYSTEM_PROMPT: &str = r#"You are an expert software engineer synthesizing commit message proposals that were generated from different subsets of the same commit's file diffs.

Because the commit's diff was too large for a single request, it was split into N chunks and each chunk produced a partial proposed message. You now see all partial messages together with the commit's full `diff --stat` summary and the original commit message.

Your task:
1. **Synthesize** a single cohesive conventional commit message that accurately describes ALL changes in the commit
2. **Choose type and scope** that best represent the overall change — if partial messages disagree, pick the one that covers the broadest set of changes
3. **Preserve details** from each partial message — do not lose important information about what changed
4. **Write a body** when the combined scope warrants it — summarize the key changes from all chunks
5. **Use conventional commit format**: `type(scope): subject` with optional body after a blank line

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

amendments:
  - commit: "full-40-character-sha1-hash"
    message: |
      type(scope): subject line

      Body paragraph synthesized from all chunks.

IMPORTANT:
- Return exactly ONE amendment for this commit
- Preserve the commit hash exactly as given
- Use YAML literal block scalar (|) for multi-line messages
- Your response must start with "amendments:" and be valid YAML only"#;

/// Generates the user prompt for a chunk-merge reduce pass.
///
/// Lists each partial amendment with its index and covered files, plus the
/// original message and full `diff --stat` summary for context.
pub(crate) fn generate_chunk_merge_user_prompt(
    commit_hash: &str,
    original_message: &str,
    diff_summary: &str,
    chunk_amendments: &[crate::data::amendments::Amendment],
) -> String {
    let mut prompt = format!(
        "Merge the following partial amendments for commit {commit_hash} into a single cohesive message.\n\n"
    );

    prompt.push_str(&format!(
        "Original message:\n{}\n\n",
        indent_message(original_message, "  "),
    ));

    prompt.push_str(&format!(
        "Full diff --stat summary:\n{}\n\n",
        indent_message(diff_summary, "  "),
    ));

    prompt.push_str(&format!(
        "Partial amendments ({} chunks):\n\n",
        chunk_amendments.len()
    ));

    for (i, amendment) in chunk_amendments.iter().enumerate() {
        prompt.push_str(&format!(
            "Chunk {}:\n  Proposed message: |\n{}\n\n",
            i + 1,
            indent_message(&amendment.message, "    "),
        ));
    }

    prompt
        .push_str("Synthesize these into a single amendment. Return exactly one amendment entry.");

    prompt
}

/// System prompt for merging partial chunk check results into a single check result.
///
/// When a commit's diff is too large for one AI request, it is split into
/// file-level chunks and each chunk produces partial check results. This
/// prompt drives a reduce pass that synthesizes per-chunk suggestions and
/// summaries into one cohesive result. Issues are merged deterministically
/// (union + dedup) outside this prompt.
pub(crate) const CHECK_CHUNK_MERGE_SYSTEM_PROMPT: &str = r#"You are an expert commit message reviewer synthesizing check results that were generated from different subsets of the same commit's file diffs.

Because the commit's diff was too large for a single request, it was split into N chunks and each chunk produced a partial suggestion for improving the commit message. You now see all partial suggestions together with the commit's original message and full `diff --stat` summary.

Your task:
1. **Synthesize** a single cohesive commit message suggestion that incorporates insights from ALL partial suggestions
2. **Choose type and scope** that best represent the overall change — if partial suggestions disagree, pick the one that covers the broadest set of changes
3. **Preserve accuracy feedback** from each partial suggestion — do not lose important corrections about what changed
4. **Write a brief summary** of what the commit changes (one sentence, factual)

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

checks:
  - commit: "full-40-character-sha1-hash"
    passes: false
    issues: []
    suggestion:
      message: |
        type(scope): subject line

        Body paragraph synthesized from all chunks.
      explanation: |
        Combined improvements from all partial reviews.
    summary: "One sentence describing what this commit changes"

IMPORTANT:
- Return exactly ONE check entry for this commit
- Preserve the commit hash exactly as given
- The `issues` array must be empty — issues are merged separately
- The `passes` field must match the value provided below
- Use YAML literal block scalar (|) for multi-line messages
- Your response must start with "checks:" and be valid YAML only"#;

/// Generates the user prompt for a check chunk-merge reduce pass.
///
/// Lists each partial suggestion with its index, plus the original message,
/// full `diff --stat` summary, and the deterministically-merged pass status
/// for context.
pub(crate) fn generate_check_chunk_merge_user_prompt(
    commit_hash: &str,
    original_message: &str,
    diff_summary: &str,
    passes: bool,
    chunk_suggestions: &[&crate::data::check::CommitSuggestion],
    chunk_summaries: &[Option<&str>],
) -> String {
    let mut prompt = format!(
        "Merge the following partial check suggestions for commit {commit_hash} into a single cohesive result.\n\n"
    );

    prompt.push_str(&format!(
        "Original message:\n{}\n\n",
        indent_message(original_message, "  "),
    ));

    prompt.push_str(&format!(
        "Full diff --stat summary:\n{}\n\n",
        indent_message(diff_summary, "  "),
    ));

    prompt.push_str(&format!("Overall passes: {passes}\n\n"));

    prompt.push_str(&format!(
        "Partial suggestions ({} chunks):\n\n",
        chunk_suggestions.len()
    ));

    for (i, suggestion) in chunk_suggestions.iter().enumerate() {
        let summary_text = chunk_summaries.get(i).and_then(|s| *s).unwrap_or("(none)");
        prompt.push_str(&format!(
            "Chunk {}:\n  Suggested message: |\n{}\n  Explanation: |\n{}\n  Summary: {}\n\n",
            i + 1,
            indent_message(&suggestion.message, "    "),
            indent_message(&suggestion.explanation, "    "),
            summary_text,
        ));
    }

    prompt.push_str(
        "Synthesize these into a single check entry with one suggestion and one summary. Return exactly one check entry.",
    );

    prompt
}

/// System prompt for merging per-commit PR content into a unified PR description.
///
/// When a PR's combined diff is too large for a single AI request, each commit
/// is processed individually to produce a partial PR title and description.
/// This prompt drives a reduce pass that synthesizes per-commit results into
/// one cohesive PR title and description.
pub(crate) const PR_CONTENT_MERGE_SYSTEM_PROMPT: &str = r#"You are a software engineer synthesizing a pull request description from partial descriptions that were generated from individual commits.

Because the PR's combined diff was too large for a single request, each commit was processed individually and produced a partial PR title and description. You now see all partial results together with the PR template.

Your task:
1. **Synthesize** a single unified PR title that covers the overall change set
2. **Combine** the per-commit descriptions into a coherent PR description that follows the template structure
3. **Preserve details** from each partial description — do not lose important information
4. **Avoid redundancy** — merge overlapping content rather than repeating it
5. **Follow the PR template** structure if one is provided

CRITICAL RESPONSE FORMAT: Respond with ONLY valid YAML content. Do not include explanatory text, markdown wrappers, or code blocks.

Your response must follow this exact YAML structure:

title: "Concise PR title covering the overall change"
description: |
  Full PR description in markdown format.

IMPORTANT:
- The title should be concise (50-80 characters) and cover the overall change
- The description should synthesize all per-commit descriptions into a coherent narrative
- Your response must be valid YAML only"#;

/// Generates the user prompt for a PR content merge reduce pass.
///
/// Lists each per-commit PR content with its index, plus the PR template
/// for structural guidance.
pub(crate) fn generate_pr_content_merge_user_prompt(
    per_commit_contents: &[crate::cli::git::PrContent],
    pr_template: &str,
) -> String {
    let mut prompt = String::from(
        "Synthesize the following per-commit PR descriptions into a single unified PR.\n\n",
    );

    if !pr_template.is_empty() {
        prompt.push_str(&format!(
            "PR template:\n{}\n\n",
            indent_message(pr_template, "  "),
        ));
    }

    prompt.push_str(&format!(
        "Per-commit descriptions ({} commits):\n\n",
        per_commit_contents.len()
    ));

    for (i, content) in per_commit_contents.iter().enumerate() {
        prompt.push_str(&format!(
            "Commit {}:\n  Title: {}\n  Description: |\n{}\n\n",
            i + 1,
            content.title,
            indent_message(&content.description, "    "),
        ));
    }

    prompt.push_str(
        "Synthesize these into a single PR with one title and one description. Return exactly one PR entry.",
    );

    prompt
}

/// Generates the user prompt for an amendment coherence pass.
pub fn generate_amendment_coherence_user_prompt(
    items: &[(crate::data::amendments::Amendment, String)],
) -> String {
    let mut prompt = String::from(
        "Review the following individually-generated commit message amendments for cross-commit coherence:\n\n",
    );

    for (i, (amendment, summary)) in items.iter().enumerate() {
        prompt.push_str(&format!(
            "{}. Commit: {}\n   Proposed message: |\n{}\n   Summary: {}\n\n",
            i + 1,
            amendment.commit,
            indent_message(&amendment.message, "     "),
            summary,
        ));
    }

    prompt.push_str("Refine these amendments for cross-commit coherence. Return ALL commits in the amendments array, including those that need no changes.");

    prompt
}

/// Generates the user prompt for a check coherence pass.
pub fn generate_check_coherence_user_prompt(
    items: &[(crate::data::check::CommitCheckResult, String)],
) -> String {
    let mut prompt = String::from(
        "Review the following individually-generated check results for cross-commit coherence:\n\n",
    );

    for (i, (result, summary)) in items.iter().enumerate() {
        prompt.push_str(&format!(
            "{}. Commit: {} ({})\n   Message: {}\n   Passes: {}\n   Issues: {}\n   Summary: {}\n\n",
            i + 1,
            result.hash,
            if result.passes { "PASS" } else { "FAIL" },
            result.message,
            result.passes,
            result.issues.len(),
            summary,
        ));
    }

    prompt.push_str("Refine these check results for cross-commit coherence. Return ALL commits in the checks array.");

    prompt
}

/// Indents each line of a message with the given prefix.
fn indent_message(message: &str, prefix: &str) -> String {
    message
        .lines()
        .map(|line| format!("{prefix}{line}"))
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::context::*;

    fn make_context() -> CommitContext {
        CommitContext {
            project: ProjectContext {
                commit_guidelines: None,
                pr_guidelines: None,
                valid_scopes: Vec::new(),
                ..ProjectContext::default()
            },
            branch: BranchContext {
                work_type: WorkType::Feature,
                description: "add feature".to_string(),
                is_feature_branch: true,
                ..BranchContext::default()
            },
            range: CommitRangeContext::default(),
            files: Vec::new(),
            user_provided: None,
        }
    }

    // ── indent_message ─────────────────────────────────────────────

    #[test]
    fn indent_single_line() {
        assert_eq!(indent_message("hello", "  "), "  hello");
    }

    #[test]
    fn indent_multiple_lines() {
        let result = indent_message("line1\nline2\nline3", ">> ");
        assert_eq!(result, ">> line1\n>> line2\n>> line3");
    }

    #[test]
    fn indent_empty_string() {
        // "".lines() yields zero items, so join produces ""
        assert_eq!(indent_message("", "  "), "");
    }

    // ── generate_user_prompt ───────────────────────────────────────

    #[test]
    fn user_prompt_contains_yaml() {
        let prompt = generate_user_prompt("commits:\n  - hash: abc123");
        assert!(prompt.contains("commits:\n  - hash: abc123"));
        assert!(prompt.contains("CRITICAL ANALYSIS STEPS"));
    }

    #[test]
    fn user_prompt_requires_all_commits() {
        let prompt = generate_user_prompt("test");
        assert!(prompt.contains("exactly one amendment per entry"));
        assert!(prompt.contains("Do not skip any commit"));
        assert!(prompt.contains("do not emit more amendments"));
    }

    // ── generate_contextual_system_prompt ──────────────────────────

    #[test]
    fn contextual_system_prompt_contains_base() {
        let context = make_context();
        let prompt = generate_contextual_system_prompt(&context);
        assert!(prompt.contains("expert software engineer"));
        assert!(prompt.contains("CONTEXTUAL INTELLIGENCE GUIDELINES"));
    }

    #[test]
    fn contextual_system_prompt_with_branch_context() {
        let context = make_context();
        let prompt = generate_contextual_system_prompt(&context);
        assert!(prompt.contains("add feature"));
    }

    #[test]
    fn contextual_system_prompt_with_guidelines_claude() {
        let mut context = make_context();
        context.project.commit_guidelines = Some("Use type(scope): desc".to_string());
        let prompt = generate_contextual_system_prompt_for_provider(&context, PromptStyle::Claude);
        assert!(prompt.contains("MANDATORY COMMIT MESSAGE TEMPLATE"));
        assert!(prompt.contains("Use type(scope): desc"));
    }

    #[test]
    fn contextual_system_prompt_with_guidelines_openai() {
        let mut context = make_context();
        context.project.commit_guidelines = Some("Use type(scope): desc".to_string());
        let prompt = generate_contextual_system_prompt_for_provider(&context, PromptStyle::OpenAi);
        assert!(prompt.contains("PROJECT COMMIT GUIDELINES"));
        assert!(!prompt.contains("MANDATORY COMMIT MESSAGE TEMPLATE"));
    }

    #[test]
    fn contextual_system_prompt_with_scopes() {
        let mut context = make_context();
        context.project.valid_scopes = vec![ScopeDefinition {
            name: "cli".to_string(),
            description: "CLI module".to_string(),
            examples: Vec::new(),
            file_patterns: Vec::new(),
        }];
        let prompt = generate_contextual_system_prompt(&context);
        assert!(prompt.contains("cli: CLI module"));
    }

    #[test]
    fn contextual_system_prompt_work_pattern_refactoring() {
        let mut context = make_context();
        context.range.work_pattern = WorkPattern::Refactoring;
        let prompt = generate_contextual_system_prompt(&context);
        assert!(prompt.contains("Refactoring work"));
    }

    #[test]
    fn contextual_system_prompt_scope_consistency() {
        let mut context = make_context();
        context.range.scope_consistency = ScopeAnalysis {
            consistent_scope: Some("cli".to_string()),
            scope_changes: vec!["cli".to_string()],
            confidence: 0.9,
        };
        let prompt = generate_contextual_system_prompt(&context);
        assert!(prompt.contains("'cli' scope"));
    }

    // ── generate_contextual_user_prompt ────────────────────────────

    #[test]
    fn contextual_user_prompt_no_guidelines_uses_default() {
        let context = make_context();
        let prompt = generate_contextual_user_prompt("yaml-data", &context);
        assert!(prompt.contains("COMMIT GUIDELINES"));
    }

    #[test]
    fn contextual_user_prompt_with_guidelines_skips_default() {
        let mut context = make_context();
        context.project.commit_guidelines = Some("custom guidelines".to_string());
        let prompt = generate_contextual_user_prompt("yaml-data", &context);
        assert!(!prompt.contains("=== COMMIT GUIDELINES ==="));
    }

    #[test]
    fn contextual_user_prompt_significant_change() {
        let mut context = make_context();
        context.range.architectural_impact = ArchitecturalImpact::Breaking;
        let prompt = generate_contextual_user_prompt("yaml-data", &context);
        assert!(prompt.contains("significant changes"));
    }

    // ── generate_check_system_prompt ───────────────────────────────

    #[test]
    fn check_system_prompt_default_guidelines() {
        let prompt = generate_check_system_prompt(None);
        assert!(prompt.contains("commit message reviewer"));
        assert!(prompt.contains("PROJECT COMMIT GUIDELINES"));
    }

    #[test]
    fn check_system_prompt_custom_guidelines() {
        let prompt = generate_check_system_prompt(Some("My custom rules"));
        assert!(prompt.contains("My custom rules"));
    }

    #[test]
    fn check_system_prompt_with_scopes() {
        let scopes = vec![ScopeDefinition {
            name: "cli".to_string(),
            description: "CLI module".to_string(),
            examples: Vec::new(),
            file_patterns: Vec::new(),
        }];
        let prompt = generate_check_system_prompt_with_scopes(None, &scopes);
        assert!(prompt.contains("VALID SCOPES"));
        assert!(prompt.contains("`cli`: CLI module"));
    }

    // ── generate_check_user_prompt ─────────────────────────────────

    #[test]
    fn check_user_prompt_with_suggestions() {
        let prompt = generate_check_user_prompt("yaml-data", true);
        assert!(prompt.contains("provide a corrected message"));
    }

    #[test]
    fn check_user_prompt_without_suggestions() {
        let prompt = generate_check_user_prompt("yaml-data", false);
        assert!(prompt.contains("Do NOT include suggestion"));
    }

    // ── generate_pr_description_prompt ─────────────────────────────

    #[test]
    fn pr_description_prompt_contains_template() {
        let prompt = generate_pr_description_prompt("repo-yaml", "## Description\n");
        assert!(prompt.contains("repo-yaml"));
        assert!(prompt.contains("## Description"));
    }

    // ── generate_pr_system_prompt_with_context ─────────────────────

    #[test]
    fn pr_system_prompt_claude_provider() {
        let context = make_context();
        let prompt =
            generate_pr_system_prompt_with_context_for_provider(&context, PromptStyle::Claude);
        assert!(prompt.contains("TEMPLATE HANDLING FOR CLAUDE"));
    }

    #[test]
    fn pr_system_prompt_openai_provider() {
        let context = make_context();
        let prompt =
            generate_pr_system_prompt_with_context_for_provider(&context, PromptStyle::OpenAi);
        assert!(prompt.contains("TEMPLATE FILLING INSTRUCTIONS"));
    }

    #[test]
    fn pr_system_prompt_with_pr_guidelines() {
        let mut context = make_context();
        context.project.pr_guidelines = Some("Always include screenshots".to_string());
        let prompt = generate_pr_system_prompt_with_context(&context);
        assert!(prompt.contains("PROJECT PR GUIDELINES"));
        assert!(prompt.contains("Always include screenshots"));
    }

    // ── generate_pr_description_prompt_with_context ─────────────────

    #[test]
    fn pr_description_with_context_branch_info() {
        let context = make_context();
        let prompt = generate_pr_description_prompt_with_context("yaml", "template", &context);
        assert!(prompt.contains("BRANCH CONTEXT"));
        assert!(prompt.contains("add feature"));
    }

    // ── coherence prompts ──────────────────────────────────────────

    #[test]
    fn amendment_coherence_prompt_lists_commits() {
        use crate::data::amendments::Amendment;

        let items = vec![
            (
                Amendment::new("a".repeat(40), "feat(cli): add flag".to_string()),
                "Add CLI flag".to_string(),
            ),
            (
                Amendment::new("b".repeat(40), "fix(git): fix bug".to_string()),
                "Fix git bug".to_string(),
            ),
        ];
        let prompt = generate_amendment_coherence_user_prompt(&items);
        assert!(prompt.contains(&"a".repeat(40)));
        assert!(prompt.contains(&"b".repeat(40)));
        assert!(prompt.contains("Add CLI flag"));
        assert!(prompt.contains("Fix git bug"));
    }

    #[test]
    fn check_coherence_prompt_lists_results() {
        use crate::data::check::CommitCheckResult;

        let items = vec![(
            CommitCheckResult {
                hash: "a".repeat(40),
                message: "feat: test".to_string(),
                passes: true,
                issues: Vec::new(),
                suggestion: None,
                summary: None,
            },
            "Test commit".to_string(),
        )];
        let prompt = generate_check_coherence_user_prompt(&items);
        assert!(prompt.contains(&"a".repeat(40)));
        assert!(prompt.contains("PASS"));
        assert!(prompt.contains("Test commit"));
    }

    // ── constants ──────────────────────────────────────────────────

    #[test]
    fn basic_system_prompt_not_empty() {
        assert!(BASIC_SYSTEM_PROMPT.len() > 100);
        assert!(BASIC_SYSTEM_PROMPT.contains("amendments:"));
    }

    #[test]
    fn basic_system_prompt_mentions_breaking_changes() {
        assert!(BASIC_SYSTEM_PROMPT.contains("BREAKING CHANGE DETECTION"));
    }

    #[test]
    fn basic_system_prompt_lists_breaking_change_signals() {
        for signal in [
            "MANDATORY parameter",
            "removed, renamed",
            "CLI flag",
            "MCP tool schema",
            "serialization format",
            "default-behavior change",
        ] {
            assert!(
                BASIC_SYSTEM_PROMPT.contains(signal),
                "BASIC_SYSTEM_PROMPT missing breaking-change signal: {signal:?}"
            );
        }
    }

    #[test]
    fn basic_system_prompt_calls_out_additive_looking_trap() {
        // Regression for the case where twiddle classified `feat(mcp): add
        // confirm guard` as additive even though it added a mandatory `confirm:
        // bool` to existing param structs. The prompt must explicitly warn
        // against treating new mandatory fields as additive.
        assert!(
            BASIC_SYSTEM_PROMPT.contains("ADDITIVE-LOOKING-BUT-BREAKING TRAP"),
            "BASIC_SYSTEM_PROMPT must warn against treating new mandatory fields as additive"
        );
        assert!(
            BASIC_SYSTEM_PROMPT.contains("WatcherRemoveParams"),
            "BASIC_SYSTEM_PROMPT must include the concrete params-struct example"
        );
    }

    #[test]
    fn basic_system_prompt_requires_both_breaking_markers() {
        assert!(
            BASIC_SYSTEM_PROMPT.contains("`!` immediately after the type/scope"),
            "BASIC_SYSTEM_PROMPT must require `!` after type/scope"
        );
        assert!(
            BASIC_SYSTEM_PROMPT.contains("`BREAKING CHANGE:` footer"),
            "BASIC_SYSTEM_PROMPT must require BREAKING CHANGE: footer"
        );
    }

    #[test]
    fn contextual_system_prompt_inherits_breaking_change_block() {
        let context = make_context();
        let prompt = generate_contextual_system_prompt(&context);
        assert!(
            prompt.contains("BREAKING CHANGE DETECTION"),
            "contextual system prompt must inherit BREAKING CHANGE DETECTION block from BASIC_SYSTEM_PROMPT"
        );
    }

    #[test]
    fn basic_user_prompt_has_breaking_change_final_pass() {
        let prompt = generate_user_prompt("commits: []");
        assert!(
            prompt.contains("FINAL BREAKING-CHANGE PASS"),
            "basic user prompt must end with the breaking-change final-pass nudge"
        );
        assert!(
            prompt.contains("`BREAKING CHANGE:` footer"),
            "basic user prompt must restate the BREAKING CHANGE: footer requirement"
        );
    }

    #[test]
    fn contextual_user_prompt_has_breaking_change_final_pass() {
        let context = make_context();
        let prompt = generate_contextual_user_prompt("commits: []", &context);
        assert!(
            prompt.contains("FINAL BREAKING-CHANGE PASS"),
            "contextual user prompt must end with the breaking-change final-pass nudge"
        );
    }

    #[test]
    fn pr_generation_system_prompt_not_empty() {
        assert!(PR_GENERATION_SYSTEM_PROMPT.len() > 100);
        assert!(PR_GENERATION_SYSTEM_PROMPT.contains("pull request"));
    }

    #[test]
    fn check_system_prompt_constant_not_empty() {
        assert!(CHECK_SYSTEM_PROMPT.len() > 100);
        assert!(CHECK_SYSTEM_PROMPT.contains("commit message reviewer"));
    }

    /// Regression guard for #627: in every structural YAML example in `prompt`,
    /// the `reasoning:` field must appear before the `severity:` field so the
    /// verdict is conditioned on worked-through reasoning rather than a first
    /// guess. Returns true only if both fields are present AND ordered
    /// correctly in the first occurrence.
    fn reasoning_precedes_severity(prompt: &str) -> bool {
        match (prompt.find("reasoning:"), prompt.find("severity:")) {
            (Some(r), Some(s)) => r < s,
            _ => false,
        }
    }

    #[test]
    fn check_system_prompt_puts_reasoning_before_severity() {
        assert!(
            reasoning_precedes_severity(CHECK_SYSTEM_PROMPT),
            "reasoning field must appear before severity in the YAML template"
        );
    }

    #[test]
    fn check_coherence_prompt_puts_reasoning_before_severity() {
        assert!(
            reasoning_precedes_severity(CHECK_COHERENCE_SYSTEM_PROMPT),
            "reasoning field must appear before severity in the coherence YAML template"
        );
    }

    #[test]
    fn reasoning_precedes_severity_helper_branches() {
        // Positive: both fields present, correct order.
        assert!(reasoning_precedes_severity("- reasoning: x\n  severity: y"));
        // Negative: wrong order.
        assert!(!reasoning_precedes_severity(
            "- severity: y\n  reasoning: x"
        ));
        // Negative: missing severity.
        assert!(!reasoning_precedes_severity("- reasoning: x"));
        // Negative: missing reasoning.
        assert!(!reasoning_precedes_severity("- severity: y"));
        // Negative: neither field.
        assert!(!reasoning_precedes_severity(""));
    }

    #[test]
    fn amendment_coherence_system_prompt_not_empty() {
        assert!(AMENDMENT_COHERENCE_SYSTEM_PROMPT.len() > 100);
        assert!(AMENDMENT_COHERENCE_SYSTEM_PROMPT.contains("coherence"));
    }

    #[test]
    fn check_coherence_system_prompt_not_empty() {
        assert!(CHECK_COHERENCE_SYSTEM_PROMPT.len() > 100);
    }

    #[test]
    fn chunk_merge_system_prompt_not_empty() {
        assert!(AMENDMENT_CHUNK_MERGE_SYSTEM_PROMPT.len() > 100);
        assert!(AMENDMENT_CHUNK_MERGE_SYSTEM_PROMPT.contains("amendments:"));
    }

    // ── chunk merge user prompt ──────────────────────────────────

    #[test]
    fn chunk_merge_user_prompt_includes_all_chunks() {
        use crate::data::amendments::Amendment;

        let chunks = vec![
            Amendment::new("a".repeat(40), "feat(cli): add flag".to_string()),
            Amendment::new("a".repeat(40), "feat(cli): add option".to_string()),
        ];
        let prompt = generate_chunk_merge_user_prompt(
            &"a".repeat(40),
            "original message",
            " src/main.rs | 10 ++++",
            &chunks,
        );
        assert!(prompt.contains("Chunk 1:"));
        assert!(prompt.contains("Chunk 2:"));
        assert!(prompt.contains("add flag"));
        assert!(prompt.contains("add option"));
        assert!(prompt.contains("2 chunks"));
    }

    #[test]
    fn chunk_merge_user_prompt_includes_diff_summary() {
        use crate::data::amendments::Amendment;

        let chunks = vec![Amendment::new("a".repeat(40), "feat: change".to_string())];
        let summary = " src/main.rs | 10 ++++\n src/lib.rs  |  5 ++";
        let prompt =
            generate_chunk_merge_user_prompt(&"a".repeat(40), "original", summary, &chunks);
        assert!(prompt.contains("src/main.rs | 10"));
        assert!(prompt.contains("src/lib.rs"));
        assert!(prompt.contains("original"));
    }

    #[test]
    fn check_chunk_merge_system_prompt_not_empty() {
        assert!(CHECK_CHUNK_MERGE_SYSTEM_PROMPT.len() > 100);
        assert!(CHECK_CHUNK_MERGE_SYSTEM_PROMPT.contains("checks:"));
    }

    // ── check chunk merge user prompt ───────────────────────────

    #[test]
    fn check_chunk_merge_user_prompt_includes_all_chunks() {
        use crate::data::check::CommitSuggestion;

        let suggestions = [
            CommitSuggestion {
                message: "feat(cli): add flag".to_string(),
                explanation: "improved clarity".to_string(),
            },
            CommitSuggestion {
                message: "feat(cli): add option".to_string(),
                explanation: "better scope".to_string(),
            },
        ];
        let suggestion_refs: Vec<&CommitSuggestion> = suggestions.iter().collect();
        let summaries = vec![Some("Added flag"), Some("Added option")];
        let prompt = generate_check_chunk_merge_user_prompt(
            &"a".repeat(40),
            "original message",
            " src/main.rs | 10 ++++",
            false,
            &suggestion_refs,
            &summaries,
        );
        assert!(prompt.contains("Chunk 1:"));
        assert!(prompt.contains("Chunk 2:"));
        assert!(prompt.contains("add flag"));
        assert!(prompt.contains("add option"));
        assert!(prompt.contains("2 chunks"));
        assert!(prompt.contains("passes: false"));
    }

    #[test]
    fn check_chunk_merge_user_prompt_includes_context() {
        use crate::data::check::CommitSuggestion;

        let suggestions = [CommitSuggestion {
            message: "fix: correct typo".to_string(),
            explanation: "typo in subject".to_string(),
        }];
        let suggestion_refs: Vec<&CommitSuggestion> = suggestions.iter().collect();
        let summaries = vec![Some("Fixed typo")];
        let prompt = generate_check_chunk_merge_user_prompt(
            &"b".repeat(40),
            "original",
            " src/main.rs | 5 ++\n src/lib.rs  | 3 ++",
            true,
            &suggestion_refs,
            &summaries,
        );
        assert!(prompt.contains("src/main.rs | 5"));
        assert!(prompt.contains("src/lib.rs"));
        assert!(prompt.contains("original"));
        assert!(prompt.contains("passes: true"));
        assert!(prompt.contains("Fixed typo"));
    }

    #[test]
    fn check_chunk_merge_user_prompt_handles_missing_summaries() {
        use crate::data::check::CommitSuggestion;

        let suggestions = [CommitSuggestion {
            message: "feat: change".to_string(),
            explanation: "reason".to_string(),
        }];
        let suggestion_refs: Vec<&CommitSuggestion> = suggestions.iter().collect();
        let summaries: Vec<Option<&str>> = vec![None];
        let prompt = generate_check_chunk_merge_user_prompt(
            &"c".repeat(40),
            "msg",
            " a.rs | 1 +",
            false,
            &suggestion_refs,
            &summaries,
        );
        assert!(prompt.contains("(none)"));
    }

    // ── PR content merge prompts ────────────────────────────────

    #[test]
    fn pr_content_merge_system_prompt_not_empty() {
        assert!(PR_CONTENT_MERGE_SYSTEM_PROMPT.len() > 100);
        assert!(PR_CONTENT_MERGE_SYSTEM_PROMPT.contains("title:"));
        assert!(PR_CONTENT_MERGE_SYSTEM_PROMPT.contains("description:"));
    }

    #[test]
    fn pr_content_merge_user_prompt_includes_all_commits() {
        let contents = vec![
            crate::cli::git::PrContent {
                title: "feat(a): add module a".to_string(),
                description: "Adds the a module with core logic.".to_string(),
            },
            crate::cli::git::PrContent {
                title: "feat(b): add module b".to_string(),
                description: "Adds the b module with helpers.".to_string(),
            },
        ];
        let prompt = generate_pr_content_merge_user_prompt(&contents, "## Summary\n");
        assert!(prompt.contains("Commit 1:"));
        assert!(prompt.contains("Commit 2:"));
        assert!(prompt.contains("add module a"));
        assert!(prompt.contains("add module b"));
        assert!(prompt.contains("2 commits"));
        assert!(prompt.contains("## Summary"));
    }

    #[test]
    fn pr_content_merge_user_prompt_empty_template() {
        let contents = vec![crate::cli::git::PrContent {
            title: "fix: patch".to_string(),
            description: "Patch description.".to_string(),
        }];
        let prompt = generate_pr_content_merge_user_prompt(&contents, "");
        assert!(!prompt.contains("PR template:"));
        assert!(prompt.contains("1 commits"));
        assert!(prompt.contains("fix: patch"));
    }

    #[test]
    fn system_prompt_alias() {
        assert_eq!(SYSTEM_PROMPT, BASIC_SYSTEM_PROMPT);
    }
}
