#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]

//! smix-error — ExpectationFailure + FailureCode + AI-readable
//! `to_prompt()` + `build_suggestions` (stone, cold path).
//!
//! Ported from now-retired TS source: `src/core/error.ts` + `src/core/schemas.ts:89-115`
//! (failureCodeSchema + serializedFailureSchema). v0.4 C3 buildSuggestions
//! behavior 1:1 (threshold > 0.5, top 3, score desc → field name>text
//! → DFS index asc).
//!
//! # Why a separate stone
//!
//! SDK / driver / runner-client all throw / catch `ExpectationFailure`. As
//! the canonical failure type it must live in a leaf crate that everyone
//! can depend on (cement-friendly stone). Per CLAUDE.md §9 #5: failure
//! messages MUST be AI-readable — `to_prompt()` is the canonical render.

#![doc(html_root_url = "https://docs.smix.dev/smix-error")]

use serde::{Deserialize, Serialize};
use smix_screen::ElementSummary;
use smix_selector::{Selector, describe_selector};
use std::fmt;

/// All failure codes smix surface back to the SDK / MCP / CLI. Mirrors
/// TS `failureCodeSchema` in `src/core/schemas.ts:89-99` 1:1
/// (SCREAMING_SNAKE_CASE wire).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FailureCode {
    /// Selector matched zero elements in the visible tree.
    ElementNotFound,
    /// Element matched but failed the visibility filter.
    NotVisible,
    /// Element matched but `enabled = false`.
    NotEnabled,
    /// Selector matched multiple elements (when uniqueness was required).
    Ambiguous,
    /// Operation exceeded the implicit-wait budget.
    Timeout,
    /// `expect` assertion (e.g. `toHaveText`) did not hold.
    AssertionFailed,
    /// Target app exited or never launched.
    AppNotRunning,
    /// Simulator device is not booted.
    SimulatorNotBooted,
    /// Catch-all for runner / driver / IO failures.
    DriverError,
}

/// Structured failure thrown by SDK matchers and driver calls. Shape
/// is AI-feed-back-ready (跟 TS ExpectationFailure 1:1).
///
/// `selector` is the typed `Selector` rather than the wire `serde_json::Value`
/// — callers raising failures from the driver / SDK side already have
/// the typed selector, and `to_prompt` invokes `describe_selector` for
/// stable rendering.
///
/// Serializes with TS-shape (`ok:false, code, message, selector,
/// suggestions, visibleElements, hint, screenshot, deviceLog`) — the
/// `Ok = false` discriminant matches mailrs `serializedFailureSchema`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpectationFailure {
    /// Always `false` for failures (跟 TS line 107 `z.literal(false)`).
    /// Round-trip discriminator for `Result<T, ExpectationFailure>` wire.
    pub ok: False,
    /// Failure code discriminator.
    pub code: FailureCode,
    /// Human-readable summary (and AI-readable when fed into `to_prompt`).
    pub message: String,
    /// Originating selector, when one is available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selector: Option<Selector>,
    /// Ranked near-miss suggestions (edit-distance to label / id / etc.).
    #[serde(default)]
    pub suggestions: Vec<String>,
    /// Snapshot of visible+enabled elements at failure time.
    #[serde(default)]
    pub visible_elements: Vec<ElementSummary>,
    /// Optional one-line hint (e.g. "try `app.wait_for(...)` first").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
    /// base64-encoded PNG; omitted from default rendering to keep logs lean.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub screenshot: Option<String>,
    /// v1.4 C5 — last-N-lines of captured device log, folded into
    /// AI-readable output for failure-window system context.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub device_log: Vec<String>,
}

/// Newtype around `false` — used as the [`ExpectationFailure::ok`]
/// discriminator. Serializes/deserializes as the JSON literal `false`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct False(pub bool);

/// Builder/Init form for ergonomic construction. Mirrors TS `FailureInit`.
#[derive(Default)]
pub struct FailureInit {
    /// Optional failure code (defaults to `DriverError` if `None`).
    pub code: Option<FailureCode>,
    /// Human-readable / AI-readable message.
    pub message: String,
    /// Originating selector, when one is available.
    pub selector: Option<Selector>,
    /// Pre-built ranked near-miss suggestions.
    pub suggestions: Vec<String>,
    /// Captured visible+enabled elements at failure time.
    pub visible_elements: Vec<ElementSummary>,
    /// Optional one-line hint string.
    pub hint: Option<String>,
    /// Optional base64 PNG screenshot at failure time.
    pub screenshot: Option<String>,
    /// Optional captured device log tail.
    pub device_log: Vec<String>,
}

impl ExpectationFailure {
    /// Construct from an init struct (跟 TS `new ExpectationFailure(init)`
    /// 1:1). `code` defaults to `DriverError` if init.code was None
    /// (defensive; SDK callers should always set it).
    pub fn new(init: FailureInit) -> Self {
        ExpectationFailure {
            ok: False(false),
            code: init.code.unwrap_or(FailureCode::DriverError),
            message: init.message,
            selector: init.selector,
            suggestions: init.suggestions,
            visible_elements: init.visible_elements,
            hint: init.hint,
            screenshot: init.screenshot,
            device_log: init.device_log,
        }
    }

    /// AI-facing rendering. Designed so the output can be pasted back
    /// as a user message into a coding agent (跟 TS toPrompt 1:1).
    #[must_use]
    pub fn to_prompt(&self) -> String {
        let mut lines: Vec<String> = Vec::new();
        lines.push(format!(
            "FAIL [{}]: {}",
            format_code(self.code),
            self.message
        ));
        if let Some(sel) = &self.selector {
            lines.push(format!("  selector: {}", describe_selector(sel)));
        }
        if !self.suggestions.is_empty() {
            lines.push("  suggestions:".into());
            for s in &self.suggestions {
                lines.push(format!("    - {}", s));
            }
        }
        if !self.visible_elements.is_empty() {
            let n = self.visible_elements.len().min(10);
            lines.push(format!("  visible elements (top {}):", n));
            for el in self.visible_elements.iter().take(10) {
                lines.push(format!("    - {}", render_element(el)));
            }
        }
        if let Some(h) = &self.hint {
            lines.push(format!("  hint: {}", h));
        }
        if !self.device_log.is_empty() {
            // v1.4 C5 LOG_PROMPT_CAP — defensive ceiling for AI prompt size.
            const LOG_PROMPT_CAP: usize = 200;
            let n = self.device_log.len();
            lines.push(format!("  device log (last {} lines):", n));
            let start = n.saturating_sub(LOG_PROMPT_CAP);
            for dl in &self.device_log[start..] {
                lines.push(format!("    - {}", dl));
            }
        }
        lines.join("\n")
    }
}

impl fmt::Display for ExpectationFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_prompt())
    }
}

impl std::error::Error for ExpectationFailure {}

fn format_code(c: FailureCode) -> &'static str {
    match c {
        FailureCode::ElementNotFound => "ELEMENT_NOT_FOUND",
        FailureCode::NotVisible => "NOT_VISIBLE",
        FailureCode::NotEnabled => "NOT_ENABLED",
        FailureCode::Ambiguous => "AMBIGUOUS",
        FailureCode::Timeout => "TIMEOUT",
        FailureCode::AssertionFailed => "ASSERTION_FAILED",
        FailureCode::AppNotRunning => "APP_NOT_RUNNING",
        FailureCode::SimulatorNotBooted => "SIMULATOR_NOT_BOOTED",
        FailureCode::DriverError => "DRIVER_ERROR",
    }
}

fn render_element(el: &ElementSummary) -> String {
    let role_str = el.role.map(|r| r.as_str()).unwrap_or("unknown");
    let mut bits: Vec<String> = vec![role_str.to_string()];
    if let Some(n) = &el.name {
        bits.push(format!("name={:?}", n));
    }
    if let Some(i) = &el.id {
        bits.push(format!("id=\"{}\"", i));
    }
    if let Some(t) = &el.text
        && Some(t) != el.name.as_ref()
    {
        bits.push(format!("text={:?}", t));
    }
    if !el.enabled {
        bits.push("disabled".into());
    }
    bits.join(" ")
}

// -------------------- buildSuggestions ----------------------------------

const SUGGESTION_THRESHOLD: f64 = 0.5;
const SUGGESTION_TOP_N: usize = 3;

/// Generate "Did you mean ...?" suggestions from the current visible
/// element list (跟 TS `buildSuggestions` 1:1, v0.4 C3 contract:
/// threshold > 0.5, top 3, score desc → field name > text → DFS index asc).
///
/// `target = None` → empty vec.
#[must_use]
pub fn build_suggestions(target: Option<&str>, visible: &[ElementSummary]) -> Vec<String> {
    let Some(target) = target else {
        return Vec::new();
    };
    let lower_target = target.to_lowercase();
    let mut candidates: Vec<(f64, &'static str, String, usize)> = Vec::new();
    for (i, el) in visible.iter().enumerate() {
        let mut best: Option<(f64, &'static str, String)> = None;
        if let Some(name) = &el.name
            && !name.is_empty()
        {
            let s = similarity(&name.to_lowercase(), &lower_target);
            if s > SUGGESTION_THRESHOLD {
                best = Some((s, "name", name.clone()));
            }
        }
        if let Some(text) = &el.text
            && !text.is_empty()
        {
            let s = similarity(&text.to_lowercase(), &lower_target);
            if s > SUGGESTION_THRESHOLD && best.as_ref().map(|(bs, _, _)| s > *bs).unwrap_or(true) {
                best = Some((s, "text", text.clone()));
            }
        }
        if let Some((score, field, value)) = best {
            candidates.push((score, field, value, i));
        }
    }
    // Sort: score desc → field name>text → index asc.
    candidates.sort_by(|a, b| {
        b.0.partial_cmp(&a.0)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| match (a.1, b.1) {
                ("name", "text") => std::cmp::Ordering::Less,
                ("text", "name") => std::cmp::Ordering::Greater,
                _ => std::cmp::Ordering::Equal,
            })
            .then_with(|| a.3.cmp(&b.3))
    });
    candidates
        .into_iter()
        .take(SUGGESTION_TOP_N)
        .map(|(score, field, value, _)| {
            format!(
                "Did you mean {:?}? (similarity {:.2}, field {})",
                value, score, field
            )
        })
        .collect()
}

/// Normalized `[0, 1]` string similarity. 1=identical, 0=completely different.
/// (跟 TS `similarity` 1:1.)
#[must_use]
pub fn similarity(a: &str, b: &str) -> f64 {
    if a == b {
        return 1.0;
    }
    let (longer, shorter) = if a.chars().count() >= b.chars().count() {
        (a, b)
    } else {
        (b, a)
    };
    let llen = longer.chars().count();
    if llen == 0 {
        return 1.0;
    }
    let dist = edit_distance(longer, shorter);
    (llen as f64 - dist as f64) / llen as f64
}

/// Levenshtein edit distance (Wagner-Fischer, 跟 TS line 215-230 1:1).
#[must_use]
pub fn edit_distance(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();
    let a_len = a_chars.len();
    let b_len = b_chars.len();
    let mut dp: Vec<usize> = (0..=b_len).collect();
    for i in 1..=a_len {
        let mut prev = dp[0];
        dp[0] = i;
        for j in 1..=b_len {
            let tmp = dp[j];
            dp[j] = if a_chars[i - 1] == b_chars[j - 1] {
                prev
            } else {
                1 + dp[j].min(dp[j - 1]).min(prev)
            };
            prev = tmp;
        }
    }
    dp[b_len]
}
