import requests
from .models import ServiceSetting

class BaseClient:
    def __init__(self, name):
        try:
            self.setting = ServiceSetting.objects.get(name=name, is_active=True)
            self.url = self.setting.url.rstrip('/')
            self.api_key = self.setting.api_key
        except ServiceSetting.DoesNotExist:
            self.setting = None
            self.url = None
            self.api_key = None

    def is_configured(self):
        return self.url and self.api_key

class JellyfinClient(BaseClient):
    def __init__(self):
        super().__init__('jellyfin')

    def get_info(self):
        if not self.is_configured(): return None
        try:
            headers = {'X-Emby-Token': self.api_key}
            resp = requests.get(f"{self.url}/System/Info", headers=headers, timeout=5)
            if resp.status_code == 200:
                return resp.json()
        except:
            pass
        return None

    def get_recent_items(self, limit=5):
        if not self.is_configured(): return []
        try:
            headers = {'X-Emby-Token': self.api_key}
            # Get latest media
            resp = requests.get(f"{self.url}/Users/Public/Items/Latest?Limit={limit}", headers=headers, timeout=5)
            if resp.status_code == 200:
                return resp.json()
        except:
            pass
        return []

class RadarrClient(BaseClient):
    def __init__(self):
        super().__init__('radarr')

    def get_status(self):
        if not self.is_configured(): return None
        try:
            params = {'apikey': self.api_key}
            resp = requests.get(f"{self.url}/api/v3/system/status", params=params, timeout=5)
            if resp.status_code == 200:
                return resp.json()
        except:
            pass
        return None

    def get_queue(self):
        if not self.is_configured(): return []
        try:
            params = {'apikey': self.api_key}
            resp = requests.get(f"{self.url}/api/v3/queue", params=params, timeout=5)
            if resp.status_code == 200:
                return resp.json().get('records', [])
        except:
            pass
        return []

class SonarrClient(BaseClient):
    def __init__(self):
        super().__init__('sonarr')

    def get_status(self):
        if not self.is_configured(): return None
        try:
            params = {'apikey': self.api_key}
            resp = requests.get(f"{self.url}/api/v3/system/status", params=params, timeout=5)
            if resp.status_code == 200:
                return resp.json()
        except:
            pass
        return None

    def get_queue(self):
        if not self.is_configured(): return []
        try:
            params = {'apikey': self.api_key}
            resp = requests.get(f"{self.url}/api/v3/queue", params=params, timeout=5)
            if resp.status_code == 200:
                return resp.json().get('records', [])
        except:
            pass
        return []

class JellyseerrClient(BaseClient):
    def __init__(self):
        super().__init__('jellyseerr')

    def get_status(self):
        if not self.is_configured(): return None
        try:
            headers = {'X-Api-Key': self.api_key}
            resp = requests.get(f"{self.url}/api/v1/status", headers=headers, timeout=5)
            if resp.status_code == 200:
                return resp.json()
        except:
            pass
        return None

    def get_requests(self, count=5):
        if not self.is_configured(): return []
        try:
            headers = {'X-Api-Key': self.api_key}
            resp = requests.get(f"{self.url}/api/v1/request?take={count}&skip=0&filter=all", headers=headers, timeout=5)
            if resp.status_code == 200:
                return resp.json().get('results', [])
        except:
            pass
        return []