import requests


class InfoCuaca:
    def __init__(self):
        self.base_url = "https://api.open-meteo.com/v1/forecast"

    def checkweather(self, city: str):
        location = {
            "jakarta": {"lat": -6.21, "lon": 106.84},
            "bandung": {"lat": -6.91, "lon": 107.60},
            "surabaya": {"lat": -7.25, "lon": 112.75},
        }

        city = city.lower()

        if city in location:
            lat = location[city]["lat"]
            lon = location[city]["lon"]
            params = {"latitude": lat, "longitude": lon, "current_weather": True}

            headers = {"User-Agent": "WeatherScanner/0.1"}
            try:
                res = requests.get(
                    self.base_url, 
                    params=params, 
                    headers=headers, 
                    timeout=10
                )
                
                if res.status_code != 200:
                    return f"API Error {res.status_code}: {res.text[:50]}"

                data = res.json()

                if "error" in data:
                    return f"API Error: {data.get('reason', 'Unknown error')}"
                
                suhu = data["current_weather"]["temperature"]
                return f"Suhu now at {city.capitalize()} is {suhu}C"

            except requests.exceptions.JSONDecodeError:
                return f"DEBUG - Server mengirim ini: {res.text[:200]}"

            except requests.exceptions.RequestException as e:
                return f"Masalah Koneksi: {str(e)}"

            except KeyError:
                return "Error: Format data dari API berubah (Suhu tidak ditemukan)."
        else:
            return "Sorry, city not register"


if __name__ == '__main__':
    app = InfoCuaca()
    print(app.checkweather('jakarta'))