import requests
from .models import ServiceSetting
from .api_clients import JellyfinClient, RadarrClient, SonarrClient, JellyseerrClient

def check_service_status(service_name):
    try:
        setting = ServiceSetting.objects.get(name=service_name, is_active=True)
        if not setting.url:
            return {"status": "Not Configured", "details": None}
        
        # Detailed check
        if service_name == 'jellyfin':
            client = JellyfinClient()
            info = client.get_info()
            if info:
                return {"status": "Online", "details": f"Version: {info.get('Version')}"}
        elif service_name == 'radarr':
            client = RadarrClient()
            info = client.get_status()
            if info:
                return {"status": "Online", "details": f"Version: {info.get('version')}"}
        elif service_name == 'sonarr':
            client = SonarrClient()
            info = client.get_status()
            if info:
                return {"status": "Online", "details": f"Version: {info.get('version')}"}
        elif service_name == 'jellyseerr':
            client = JellyseerrClient()
            info = client.get_status()
            if info:
                return {"status": "Online", "details": f"Version: {info.get('version')}"}

        # Fallback to simple ping
        response = requests.get(setting.url, timeout=5)
        if response.status_code < 400:
            return {"status": "Online", "details": "Reachable (No API details)"}
        else:
            return {"status": "Error", "details": f"Status: {response.status_code}"}
            
    except ServiceSetting.DoesNotExist:
        return {"status": "Not Configured", "details": None}
    except Exception as e:
        return {"status": "Offline", "details": str(e)}

def get_all_services_status():
    services = ['jellyfin', 'radarr', 'sonarr', 'jellyseerr']
    status_map = {}
    for service in services:
        status_map[service] = check_service_status(service)
    return status_map