use axum::{
    extract::{Path, State},
    response::{Json, Response},
    body::Body,
};
use serde_json::{json, Value};

use crate::{
    error::ApiError,
    AppState,
};

pub async fn get_stream_status(
    State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
    let owncast_service = state.owncast_service.as_ref()
        .ok_or_else(|| ApiError::Internal("Owncast service not configured".to_string()))?;

    let stream_info = owncast_service.get_stream_info().await
        .map_err(|e| ApiError::Internal(format!("Failed to get stream status: {}", e)))?;

    Ok(Json(json!({
        "is_live": stream_info.is_live,
        "stream_url": stream_info.stream_url,
        "viewer_count": stream_info.viewer_count,
        "stream_title": stream_info.stream_title,
        "last_connect_time": stream_info.last_connect_time,
        "last_disconnect_time": stream_info.last_disconnect_time
    })))
}

pub async fn get_live_status(
    State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
    let owncast_service = state.owncast_service.as_ref()
        .ok_or_else(|| ApiError::Internal("Owncast service not configured".to_string()))?;

    let status = owncast_service.get_status().await
        .map_err(|e| ApiError::Internal(format!("Failed to get live status: {}", e)))?;

    Ok(Json(json!({
        "online": status.online,
        "viewer_count": status.viewer_count,
        "stream_title": status.stream_title,
        "last_connect_time": status.last_connect_time,
        "last_disconnect_time": status.last_disconnect_time
    })))
}

/// Proxy HLS playlist to avoid CORS issues
pub async fn proxy_hls_playlist(
    State(state): State<AppState>,
) -> Result<Response, ApiError> {
    let owncast_service = state.owncast_service
        .ok_or_else(|| ApiError::Internal("Owncast service not available".to_string()))?;
    
    // Use reqwest directly with the known URL structure
    let client = reqwest::Client::new();
    let url = "https://stream.rockvilletollandsda.church/hls/stream.m3u8";
    
    let response = client
        .get(url)
        .send()
        .await
        .map_err(|e| ApiError::Internal(format!("Failed to fetch HLS playlist: {}", e)))?;
    
    if !response.status().is_success() {
        return Err(ApiError::Internal(format!("HLS playlist request failed: {}", response.status())));
    }
    
    let content = response.bytes().await
        .map_err(|e| ApiError::Internal(format!("Failed to read HLS content: {}", e)))?;
    
    Ok(Response::builder()
        .status(200)
        .header("Content-Type", "application/vnd.apple.mpegurl")
        .header("Cache-Control", "no-cache")
        .body(Body::from(content))
        .map_err(|e| ApiError::Internal(format!("Failed to build response: {}", e)))?)
}

/// Proxy HLS variant playlists (0/stream.m3u8, 1/stream.m3u8, etc.)
pub async fn proxy_hls_variant(
    Path(variant): Path<String>,
    State(_state): State<AppState>,
) -> Result<Response, ApiError> {
    let client = reqwest::Client::new();
    let url = format!("https://stream.rockvilletollandsda.church/hls/{}/stream.m3u8", variant);
    
    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|e| ApiError::Internal(format!("Failed to fetch HLS variant: {}", e)))?;
    
    if !response.status().is_success() {
        return Err(ApiError::Internal(format!("HLS variant request failed: {}", response.status())));
    }
    
    let content = response.bytes().await
        .map_err(|e| ApiError::Internal(format!("Failed to read HLS variant content: {}", e)))?;
    
    Ok(Response::builder()
        .status(200)
        .header("Content-Type", "application/vnd.apple.mpegurl")
        .header("Cache-Control", "no-cache")
        .body(Body::from(content))
        .map_err(|e| ApiError::Internal(format!("Failed to build response: {}", e)))?)
}

/// Proxy HLS segment files (.ts files)
pub async fn proxy_hls_segment(
    Path((variant, segment)): Path<(String, String)>,
    State(_state): State<AppState>,
) -> Result<Response, ApiError> {
    let client = reqwest::Client::new();
    let url = format!("https://stream.rockvilletollandsda.church/hls/{}/{}", variant, segment);
    
    let response = client
        .get(&url)
        .send()
        .await
        .map_err(|e| ApiError::Internal(format!("Failed to fetch HLS segment: {}", e)))?;
    
    if !response.status().is_success() {
        return Err(ApiError::Internal(format!("HLS segment request failed: {}", response.status())));
    }
    
    let content = response.bytes().await
        .map_err(|e| ApiError::Internal(format!("Failed to read HLS segment content: {}", e)))?;
    
    Ok(Response::builder()
        .status(200)
        .header("Content-Type", "video/mp2t")
        .header("Cache-Control", "public, max-age=3600")
        .body(Body::from(content))
        .map_err(|e| ApiError::Internal(format!("Failed to build response: {}", e)))?)
}
