//! REST client to the external `missions` API.

use std::time::Duration;

use reqwest::{header, Client, StatusCode};
use serde_json::Value;
use tracing::warn;

use crate::internal::retry::ExponentialBackoff;
use crate::internal::schema::{validate, SchemaError};
use crate::{FetchError, MissionClientOptions};

/// HTTPS client wrapper. One instance per `MissionClient`.
#[derive(Debug, Clone)]
pub struct HttpClient {
    client: Client,
    endpoint: String,
    bearer: Option<String>,
}

impl HttpClient {
    pub fn new(opts: &MissionClientOptions) -> Result<Self, FetchError> {
        let client = Client::builder()
            .timeout(opts.request_timeout)
            .connect_timeout(opts.connect_timeout)
            .user_agent(format!("autopilot/{}", env!("CARGO_PKG_VERSION")))
            .build()
            .map_err(|e| FetchError::Internal(format!("reqwest client build: {e}")))?;
        Ok(Self {
            client,
            endpoint: opts.endpoint.clone(),
            bearer: opts.bearer_token.clone(),
        })
    }

    /// Single HTTP call — no retry. The caller (with backoff) decides what to do.
    async fn get_once(&self, mission_id: &str) -> Result<String, RawFetchError> {
        let url = format!(
            "{}/missions/{}",
            self.endpoint.trim_end_matches('/'),
            mission_id
        );
        let mut req = self
            .client
            .get(&url)
            .header(header::ACCEPT, "application/json");
        if let Some(tok) = &self.bearer {
            req = req.bearer_auth(tok);
        }
        let resp = req.send().await.map_err(|e| {
            if e.is_timeout() || e.is_connect() {
                RawFetchError::Transient(e.to_string())
            } else if e.is_request() || e.is_builder() {
                RawFetchError::Permanent(e.to_string())
            } else {
                RawFetchError::Transient(e.to_string())
            }
        })?;

        let status = resp.status();
        let body = resp
            .text()
            .await
            .map_err(|e| RawFetchError::Transient(format!("read body: {e}")))?;

        if status.is_success() {
            return Ok(body);
        }
        // Retry on 5xx (and treat 429 as transient too).
        if status.is_server_error() || status == StatusCode::TOO_MANY_REQUESTS {
            return Err(RawFetchError::Transient(format!(
                "http {status}: {}",
                preview(&body)
            )));
        }
        Err(RawFetchError::Permanent(format!(
            "http {status}: {}",
            preview(&body)
        )))
    }

    /// Fetch + validate + return the typed JSON value (caller deserialises into
    /// the typed model). Implements bounded exponential backoff on transient
    /// failures only; permanent failures abort immediately.
    pub async fn pull_mission_raw(
        &self,
        mission_id: &str,
        opts: &MissionClientOptions,
    ) -> Result<Value, FetchError> {
        let mut backoff = ExponentialBackoff::new(opts.backoff_base, opts.backoff_cap);

        for attempt in 1..=opts.max_attempts {
            match self.get_once(mission_id).await {
                Ok(body) => {
                    let value = validate(&body).map_err(|e| match e {
                        SchemaError::Invalid { messages, sample } => {
                            FetchError::SchemaInvalid { messages, sample }
                        }
                        SchemaError::ParseJson { message, sample } => FetchError::SchemaInvalid {
                            messages: vec![message],
                            sample,
                        },
                    })?;
                    return Ok(value);
                }
                Err(RawFetchError::Permanent(reason)) => {
                    return Err(FetchError::Permanent(reason));
                }
                Err(RawFetchError::Transient(reason)) => {
                    warn!(
                        component = "mission_client",
                        attempt,
                        max = opts.max_attempts,
                        reason = %reason,
                        "transient fetch failure"
                    );
                    if attempt < opts.max_attempts {
                        tokio::time::sleep(backoff.next_delay()).await;
                        continue;
                    }
                }
            }
        }
        Err(FetchError::MaxRetriesExceeded {
            attempts: opts.max_attempts,
        })
    }
}

#[derive(Debug)]
enum RawFetchError {
    Transient(String),
    Permanent(String),
}

fn preview(body: &str) -> String {
    let cap = 256;
    if body.len() <= cap {
        body.to_owned()
    } else {
        format!("{}…", &body[..cap])
    }
}

#[allow(dead_code)] // Used for diagnostic output and by future health detail.
pub fn default_request_timeout() -> Duration {
    Duration::from_secs(5)
}
