//! Truthfulness guards: ExecutionTruth, ModelIdentityTruth, CurrentEventsTruth,
//! LiteraryQuoteRetry, PersonalityIntegrity.

use crate::api::routes::agent::guard_registry::{Guard, GuardContext, GuardId, GuardVerdict};
use crate::api::routes::agent::intent_registry::Intent;

// ── 2. ExecutionTruthGuard ───────────────────────────────────────────────

pub(in crate::api::routes::agent) struct ExecutionTruthGuard;

impl Guard for ExecutionTruthGuard {
    fn id(&self) -> GuardId {
        GuardId::ExecutionTruth
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::Execution)
            || ctx.has_intent(Intent::TaskManagement)
            || ctx.has_intent(Intent::Delegation)
            || ctx.has_intent(Intent::Cron)
            || ctx.has_intent(Intent::FileDistribution)
            || ctx.has_intent(Intent::FolderScan)
            || ctx.has_intent(Intent::WalletAddressScan)
            || ctx.has_intent(Intent::ImageCountScan)
            || ctx.has_intent(Intent::MarkdownCountScan)
            || ctx.has_intent(Intent::ObsidianInsights)
            || ctx.has_intent(Intent::EmailTriage)
    }

    fn evaluate(&self, content: &str, ctx: &GuardContext) -> GuardVerdict {
        // Delegation claim verification — only fire when the semantic classifier
        // confirms the response is making a FALSE_COMPLETION claim (score > 0.7).
        // Recommendations, opinions, and analysis about delegation are NOT false
        // claims and must pass through.
        if ctx.has_intent(Intent::Delegation)
            && !ctx.tool_results.iter().any(|(name, output)| {
                let is_delegate_tool = super::behavioral::DELEGATION_TOOLS.contains(name.as_str());
                let succeeded = !output.to_ascii_lowercase().starts_with("error:");
                is_delegate_tool && succeeded
            })
        {
            let false_completion_score = ctx
                .semantic_guard_scores
                .get("FALSE_COMPLETION")
                .map(|(score, _)| *score)
                .unwrap_or(0.0);

            if false_completion_score > 0.7 {
                tracing::warn!(
                    false_completion_score,
                    "guard[ExecutionTruth]: blocked unverified delegation claim"
                );
                return GuardVerdict::Rewritten(format!(
                    "{}: by your command, execution truth is strict. I did not execute a delegated \
                     subagent task for that request. I can only claim delegated results when a \
                     subagent tool call actually runs.",
                    ctx.agent_name
                ));
            }
        }

        // Cron claim verification — uses CRON_TOOLS constant set and checks
        // for false completion claims via sentence-level heuristic.
        if ctx.has_intent(Intent::Cron) {
            let cron_tool_ran = ctx.tool_results.iter().any(|(name, output)| {
                super::behavioral::CRON_TOOLS.contains(name.as_str())
                    || name.to_ascii_lowercase().contains("cron")
                        && !output.to_ascii_lowercase().starts_with("error:")
            });
            if !cron_tool_ran {
                // Detect false completion claims via semantic classification.
                // The FALSE_COMPLETION bank captures when the model claims to
                // have completed an action that no tool execution supports.
                let false_completion_score = ctx
                    .semantic_guard_scores
                    .get("FALSE_COMPLETION")
                    .map(|(score, _trust)| *score)
                    .unwrap_or(0.0);
                if false_completion_score > 0.7 {
                    tracing::warn!(
                        "guard[ExecutionTruth]: blocked unverified cron completion claim"
                    );
                    return GuardVerdict::RetryRequested {
                        reason: "You claimed a cron job was scheduled but no cron tool was \
                                 executed. Actually schedule the cron job using the available \
                                 scheduling tools, then report the result."
                            .into(),
                    };
                }
            }
        }

        // Runtime execution prompt verification.
        let runtime_execution = ctx.has_intent(Intent::Execution)
            || ctx.has_intent(Intent::FileDistribution)
            || ctx.has_intent(Intent::FolderScan)
            || ctx.has_intent(Intent::WalletAddressScan)
            || ctx.has_intent(Intent::ImageCountScan)
            || ctx.has_intent(Intent::ObsidianInsights)
            || ctx.has_intent(Intent::EmailTriage);

        if !runtime_execution {
            return GuardVerdict::Pass;
        }

        // FIX (was L314 bug)
        if !ctx.tool_results.is_empty() {
            if denies_local_runtime_capability(content, ctx) {
                tracing::warn!(
                    "guard[ExecutionTruth]: rewriting — capability denial despite tool execution"
                );
                let tool_summary: Vec<String> = ctx
                    .tool_results
                    .iter()
                    .map(|(name, output)| {
                        let truncated: String = output.chars().take(500).collect();
                        format!("Tool `{name}` returned:\n{truncated}")
                    })
                    .collect();
                return GuardVerdict::Rewritten(format!(
                    "Here are the results:\n\n{}",
                    tool_summary.join("\n\n")
                ));
            }
            return GuardVerdict::Pass;
        }

        // No tools ran — check for false execution claims.
        let lower = content.to_ascii_lowercase();
        if lower.contains("encountered an error reaching all llm providers") {
            return GuardVerdict::Pass;
        }

        if looks_like_unexecuted_claim(content)
            || lower.contains("tool successfully executed")
            || lower.contains("the `")
            || lower.starts_with('{')
        {
            tracing::warn!("guard[ExecutionTruth]: retrying — narrated tool use without execution");
            return GuardVerdict::RetryRequested {
                reason: "You described executing a tool or producing results without actually \
                         calling any tool. Do not narrate what a tool would do — actually invoke \
                         the tool (e.g., call `bash` with the appropriate command) and report \
                         the real output."
                    .into(),
            };
        }

        if denies_local_runtime_capability(content, ctx) {
            tracing::warn!("guard[ExecutionTruth]: retrying — false capability denial");
            return GuardVerdict::RetryRequested {
                reason: "You claimed you cannot access local files or execute commands, but you \
                         have tool access. Call the `bash` tool with the appropriate command to \
                         fulfill the user's request. Do not claim inability when tools are \
                         available."
                    .into(),
            };
        }

        GuardVerdict::Pass
    }
}

fn looks_like_unexecuted_claim(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    lower.contains("\"tool_call\"")
        || lower.contains("you can use the following")
        || lower.contains("you can run")
        || lower.contains("would use the following")
        || lower.contains("crontab entry")
        || lower.contains("unable to directly execute")
}

fn denies_local_runtime_capability(response: &str, ctx: &GuardContext<'_>) -> bool {
    if ctx
        .semantic_guard_scores
        .contains_key(roboticus_llm::intent_exemplars::CAT_CAPABILITY_DENIAL)
    {
        return true;
    }
    let lower = response.to_ascii_lowercase();
    (lower.contains("can't access your files")
        || lower.contains("cannot access your files")
        || lower.contains("can't access your local files")
        || lower.contains("cannot access your local files")
        || lower.contains("can't access your folders")
        || lower.contains("cannot access your folders")
        || lower.contains("can't browse your files")
        || lower.contains("cannot browse your files")
        || lower.contains("can't write directly to your local filesystem")
        || lower.contains("cannot write directly to your local filesystem")
        || lower.contains("i'm not able to directly access")
        || lower.contains("i am not able to directly access"))
        && (lower.contains("folder")
            || lower.contains("filesystem")
            || lower.contains("device")
            || lower.contains("local"))
}

// ── 5. ModelIdentityTruthGuard ───────────────────────────────────────────

pub(in crate::api::routes::agent) struct ModelIdentityTruthGuard;

impl Guard for ModelIdentityTruthGuard {
    fn id(&self) -> GuardId {
        GuardId::ModelIdentityTruth
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::ModelIdentity)
    }

    fn evaluate(&self, content: &str, ctx: &GuardContext) -> GuardVerdict {
        // If the response is short and primarily about identity, replace it
        // with the canonical identity statement.
        let is_primarily_identity = content.len() < 200 && content.lines().count() <= 3;

        if is_primarily_identity {
            tracing::warn!(
                model = ctx.resolved_model,
                "guard[ModelIdentityTruth]: emitting canonical model identity"
            );
            return GuardVerdict::Rewritten(format!(
                "{} reporting in. I am currently running on {}.",
                ctx.agent_name, ctx.resolved_model
            ));
        }

        // For longer responses that happen to mention a model name,
        // strip the model name reference but keep the substantive content.
        // The model name is in ctx.resolved_model (e.g. "moonshot/kimi-k2-turbo-preview").
        let model = ctx.resolved_model;
        let model_short = model.split('/').next_back().unwrap_or(model);
        let cleaned = content
            .replace(model, &format!("{}'s current model", ctx.agent_name))
            .replace(model_short, &format!("{}'s model", ctx.agent_name));
        if cleaned != content {
            tracing::info!(
                model = ctx.resolved_model,
                "guard[ModelIdentityTruth]: redacted model name from substantive response"
            );
            return GuardVerdict::Rewritten(cleaned);
        }

        GuardVerdict::Pass
    }
}

// ── 5b. CurrentEventsTruthGuard ──────────────────────────────────────────

pub(in crate::api::routes::agent) struct CurrentEventsTruthGuard;

impl Guard for CurrentEventsTruthGuard {
    fn id(&self) -> GuardId {
        GuardId::CurrentEventsTruth
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::CurrentEvents)
    }

    fn evaluate(&self, content: &str, _ctx: &GuardContext) -> GuardVerdict {
        if !looks_like_stale_knowledge_disclaimer(content) {
            return GuardVerdict::Pass;
        }
        tracing::warn!("guard[CurrentEventsTruth]: blocked stale-knowledge disclaimer");
        GuardVerdict::Rewritten(
            "Acknowledged. I cannot provide a current-events sitrep from stale memory. I will \
             run live retrieval/delegation and return an up-to-date report with the current date."
                .into(),
        )
    }
}

fn looks_like_stale_knowledge_disclaimer(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    lower.contains("as of my last update")
        || lower.contains("as of my last training")
        || lower.contains("i cannot provide real-time updates")
        || lower.contains("i can't provide real-time updates")
        || lower.contains("i cannot provide real-time geopolitical analysis")
        || lower.contains("i can't provide real-time geopolitical analysis")
        || lower.contains("do not include live news feeds")
        || lower.contains("does not include live news feeds")
        || lower.contains("no live news feeds")
        || lower.contains("specialized geopolitical subagents")
        || lower.contains("as of early 2023")
        || lower.contains("as of 2023")
}

// ── 6. LiteraryQuoteRetryGuard ───────────────────────────────────────────

pub(in crate::api::routes::agent) struct LiteraryQuoteRetryGuard;

impl Guard for LiteraryQuoteRetryGuard {
    fn id(&self) -> GuardId {
        GuardId::LiteraryQuoteRetry
    }

    fn is_relevant(&self, ctx: &GuardContext) -> bool {
        ctx.has_intent(Intent::LiteraryQuoteContext)
    }

    fn evaluate(&self, content: &str, _ctx: &GuardContext) -> GuardVerdict {
        if is_overbroad_sensitive_conflict_refusal(content) {
            tracing::warn!(
                "guard[LiteraryQuoteRetry]: overbroad refusal detected; requesting retry"
            );
            GuardVerdict::RetryRequested {
                reason: "overbroad sensitive-topic refusal for literary quote request".into(),
            }
        } else {
            GuardVerdict::Pass
        }
    }
}

fn is_overbroad_sensitive_conflict_refusal(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    const MARKERS: &[&str] = &[
        "i cannot provide quotes related to ongoing conflicts",
        "i can't provide quotes related to ongoing conflicts",
        "i cannot provide quotes",
        "sensitive geopolitical situations",
        "helpful and harmless",
        "avoiding engagement with potentially harmful or biased content",
        "if you have other requests that do not involve sensitive topics",
    ];
    MARKERS.iter().any(|m| lower.contains(m))
}

// ── 7. PersonalityIntegrityGuard ─────────────────────────────────────────

pub(in crate::api::routes::agent) struct PersonalityIntegrityGuard;

impl Guard for PersonalityIntegrityGuard {
    fn id(&self) -> GuardId {
        GuardId::PersonalityIntegrity
    }

    fn is_relevant(&self, _ctx: &GuardContext) -> bool {
        true
    }

    fn evaluate(&self, content: &str, ctx: &GuardContext) -> GuardVerdict {
        if !contains_foreign_identity_boilerplate(content) {
            return GuardVerdict::Pass;
        }
        tracing::warn!("guard[PersonalityIntegrity]: stripped foreign identity boilerplate");
        let cleaned = filter_foreign_identity_sentences(content);
        if !cleaned.is_empty() {
            return GuardVerdict::Rewritten(cleaned);
        }

        let lower_prompt = ctx.user_prompt.to_ascii_lowercase();
        let asks_release_summary = lower_prompt.contains("release")
            || lower_prompt.contains("changelog")
            || lower_prompt.contains("linkedin")
            || lower_prompt.contains("x.com")
            || lower_prompt.contains("twitter")
            || lower_prompt.contains("v0.9.5")
            || lower_prompt.contains("0.9.5");
        if asks_release_summary {
            return GuardVerdict::Rewritten(
                "I need concrete Roboticus 0.9.5 context to summarize accurately. I can pull \
                 from changelog/roadmap memory if available, or you can provide release notes \
                 and I'll format them for operator, LinkedIn, and X."
                    .into(),
            );
        }
        if ctx.has_intent(Intent::ModelIdentity) {
            return GuardVerdict::Rewritten(format!(
                "I am {} and I am currently running on {}.",
                ctx.agent_name, ctx.resolved_model
            ));
        }
        GuardVerdict::Rewritten(format!(
            "I'm {}. I'll continue in my configured voice and avoid foreign boilerplate.",
            ctx.agent_name
        ))
    }
}

const FOREIGN_IDENTITY_MARKERS: &[&str] = &[
    "as an ai developed by microsoft",
    "as an ai developed by",
    "as an ai language model",
    "as an ai text-based interface",
    "as an ai, i can't",
    "as an ai, i cannot",
    "as an ai i can't",
    "as an ai i cannot",
    "as a language model",
    "i am claude",
    "i'm claude",
    "i am chatgpt",
    "i'm chatgpt",
];

fn contains_foreign_identity_boilerplate(response: &str) -> bool {
    let lower = response.to_ascii_lowercase();
    FOREIGN_IDENTITY_MARKERS.iter().any(|m| lower.contains(m))
}

fn filter_foreign_identity_sentences(response: &str) -> String {
    let mut out = String::new();
    for chunk in response.split_inclusive(['\n', '.', '!', '?']) {
        let lower = chunk.to_ascii_lowercase();
        if FOREIGN_IDENTITY_MARKERS.iter().any(|m| lower.contains(m)) {
            continue;
        }
        out.push_str(chunk);
    }
    out.trim().to_string()
}
