//! Handler for skeptic (conflict analysis) queries.

use axum::{
    extract::{Query as AxumQuery, State},
    Json,
};
use tracing::instrument;

use crate::{
    dto::{ErrorResponse, SkepticQueryParams, SkepticResponse},
    error::Result,
    state::AppState,
};

use stemedb_query::SkepticResolver;
use stemedb_storage::{GenericTrustRankStore, GenericVoteStore};

/// Query for conflict analysis using SkepticLens.
///
/// This endpoint provides "Trust but Verify" analysis, showing all competing
/// claims for a subject+predicate instead of picking a single winner.
///
/// # Response
///
/// Returns a `SkepticResponse` with:
/// - `status`: Unanimous, Agreed, or Contested
/// - `conflict_score`: 0.0 (unanimous) to 1.0 (chaos)
/// - `claims`: All distinct claims ranked by support
///
/// # Example
///
/// ```ignore
/// GET /v1/skeptic?subject=Semaglutide&predicate=muscle_effect
///
/// {
///   "status": "Contested",
///   "conflict_score": 0.72,
///   "claims": [
///     { "value": {"type": "Text", "value": "Significant loss"}, "weight_share": 0.45 },
///     { "value": {"type": "Text", "value": "Minimal loss"}, "weight_share": 0.35 }
///   ]
/// }
/// ```
#[utoipa::path(
    get,
    path = "/v1/skeptic",
    params(SkepticQueryParams),
    responses(
        (status = 200, description = "Conflict analysis successful", body = SkepticResponse),
        (status = 404, description = "No assertions found for subject+predicate", body = ErrorResponse),
        (status = 400, description = "Invalid request", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "query"
)]
#[instrument(skip(state), fields(subject = %params.subject, predicate = %params.predicate))]
pub async fn skeptic_query(
    State(state): State<AppState>,
    AxumQuery(params): AxumQuery<SkepticQueryParams>,
) -> Result<Json<SkepticResponse>> {
    // Create the resolver with vote and trust stores
    let vote_store = std::sync::Arc::new(GenericVoteStore::new(state.store.clone()));
    let trust_store = std::sync::Arc::new(GenericTrustRankStore::new(state.store.clone()));
    let resolver = SkepticResolver::new(state.store.clone(), vote_store, trust_store);

    // Execute the skeptic resolution
    let view = resolver.resolve(&params.subject, &params.predicate).await?;

    // Return 404 if no assertions found
    let view = view.ok_or_else(|| {
        crate::error::ApiError::NotFound(format!(
            "No assertions found for subject '{}' and predicate '{}'",
            params.subject, params.predicate
        ))
    })?;

    Ok(Json(view.into()))
}

#[cfg(test)]
mod tests {
    // Integration tests would go here
    // For now, the unit tests in stemedb-query cover the core functionality
}
