import requests
import pyttsx3


class AirQualityData:
    def __init__(self, city="tehran"):
        self.input_city = city.lower()
        self.data = None
        self.fetch_data()

    def fetch_data(self):
        """Fetch data from API (دریافت اطلاعات از API)"""
        try:
            url = f"http://api.waqi.info/feed/{self.input_city}/?token=a77ec062d00fbba59f2107ba7e85848113d7447e"
            response = requests.get(url).json()
            self.data = {
                "city": response['data']['city']['name'],
                "aqi": response['data']['aqi'],
                "temperature": response['data']['iaqi']['t']['v'],
                "humidity": response['data']['iaqi']['h']['v'],
                "air_pollution_level": self.air_pollution_level(response['data']['aqi'])
            }
        except Exception:
            print("Error fetching data. Please try again. (❌ خطا در دریافت اطلاعات. لطفاً دوباره تلاش کنید.)")
            self.data = None

    def air_pollution_level(self, aqi):
        """Determine air quality based on AQI (تعیین کیفیت هوا براساس مقدار AQI)"""
        aqi = int(aqi)
        if 0 <= aqi <= 50:
            return 'Good (خوب)'
        elif 51 <= aqi <= 100:
            return 'Moderate (متوسط)'
        elif 101 <= aqi <= 150:
            return 'Unhealthy for Sensitive Groups (ناسالم برای گروه‌های حساس)'
        elif 151 <= aqi <= 200:
            return 'Unhealthy (ناسالم)'
        elif 201 <= aqi <= 300:
            return 'Very Unhealthy (خیلی ناسالم)'
        else:
            return 'Hazardous (خطرناک)'

    def get_full_info(self):
        return self.data

    def get_aqi_info(self):
        return f"AQI: {self.data['aqi']} ({self.data['air_pollution_level']})"

    def get_temperature_info(self):
        return f"Temperature: {self.data['temperature']}°C (دما)"

    def get_humidity_info(self):
        return f"Humidity: {self.data['humidity']}% (رطوبت)"

    def speak_info(self):
        """Speak information (پخش اطلاعات به صورت صوتی)"""
        engine = pyttsx3.init()
        engine.setProperty('rate', 120)
        engine.say(
            f"The AQI in {self.data['city']} is {self.data['aqi']} quality {self.data['air_pollution_level']}. "
            f"The temperature is {self.data['temperature']} degrees Celsius and the humidity is {self.data['humidity']} percent.")
        print(f"The AQI in {self.data['city']} is {self.data['aqi']} quality {self.data['air_pollution_level']}. "
              f"The temperature is {self.data['temperature']} degrees Celsius and the humidity is {self.data['humidity']} percent.")
        engine.runAndWait()

    def p(self, info_type):
        """Print formatted information with emojis (چاپ اطلاعات به صورت زیبا همراه با ایموجی)"""
        if info_type == "full":
            info = self.get_full_info()
            if info is not None:
                print("===================================")
                print(f"🌍 City: {info['city']} (شهر)")
                print(f"💨 AQI: {info['aqi']} ({info['air_pollution_level']})")
                print(f"🌡 Temperature: {info['temperature']}°C (دما)")
                print(f"💧 Humidity: {info['humidity']}% (رطوبت)")
                print("===================================")
            else:
                print("No data available. (❌ داده‌ای موجود نیست.)")
        elif info_type == "aqi":
            info = self.get_aqi_info()
            print(f"💨 {info}")
        elif info_type == "temperature":
            info = self.get_temperature_info()
            print(f"🌡 {info}")
        elif info_type == "humidity":
            info = self.get_humidity_info()
            print(f"💧 {info}")
        else:
            print("Invalid information type (❌ نوع اطلاعات نامعتبر است.)")

    def r(self, info_type):
        """Return value (برگرداندن مقدار)"""
        return self._get_info_by_type(info_type)

    def pr(self, info_type):
        """Print and return value (چاپ و برگرداندن مقدار)"""
        info = self._get_info_by_type(info_type)
        print(info)
        return info

    def _get_info_by_type(self, info_type):
        if info_type == "full":
            return self.get_full_info()
        elif info_type == "aqi":
            return self.get_aqi_info()
        elif info_type == "temperature":
            return self.get_temperature_info()
        elif info_type == "humidity":
            return self.get_humidity_info()
        else:
            return "Invalid information type (❌ نوع اطلاعات نامعتبر است.)"


# Run terminal mode (اجرای حالت ترمینال)
def terminal_mode():
    city_list = {"1": "tehran", "2": "varamin", "3": "mashhad", "4": "esfahan", "5": "shiraz",
                 "6": "tabriz", "7": "karaj", "8": "rasht", "9": "ahvaz", "10": "bushehr"}
    print("City List: (📌 لیست شهرها)")
    for key, city in city_list.items():
        print(f"{key}. {city.capitalize()}")
    city_choice = input("Enter city number or city: (🔹 شماره شهر را وارد کنید) : ")
    city = city_list.get(city_choice, "tehran")
    aq = AirQualityData(city)

    while True:
        print("\nChoose an option: (✅ انتخاب کنید) : ")
        print("1. Get full information (دریافت اطلاعات کامل)")
        print("2. Get AQI (دریافت AQI)")
        print("3. Get temperature (دریافت دما)")
        print("4. Get humidity (دریافت رطوبت)")
        print("5. Audio output (خروجی صوتی)")
        print("6. Change city (تغییر شهر)")
        print("0. Exit (خروج)")

        choice = input("Enter option: (🔹 گزینه را وارد کنید:) ")
        if choice == "1":
            aq.p("full")
        elif choice == "2":
            aq.p("aqi")
        elif choice == "3":
            aq.p("temperature")
        elif choice == "4":
            aq.p("humidity")
        elif choice == "5":
            aq.speak_info()
        elif choice == "6":
            return terminal_mode()
        elif choice == "0":
            print("Goodbye! (👋 خداحافظ!)")
            break
        else:
            print("Invalid option. Try again. (❌ گزینه نامعتبر. دوباره امتحان کنید.)")

# Uncomment the following line to run terminal mode directly.

def terminal_mode():
    city_list = {"1": "tehran", "2": "varamin", "3": "mashhad", "4": "esfahan", "5": "shiraz",
                 "6": "tabriz", "7": "karaj", "8": "rasht", "9": "ahvaz", "10": "bushehr"}
    print("City List: (📌 لیست شهرها)")
    for key, city in city_list.items():
        print(f"{key}. {city.capitalize()}")
    city_choice = input("Enter city number or city: (🔹 شماره شهر را وارد کنید) : ")
    city = city_list.get(city_choice, "tehran")
    aq = AirQualityData(city)

    while True:
        print("\nChoose an option: (✅ انتخاب کنید) : ")
        print("1. Get full information (دریافت اطلاعات کامل)")
        print("2. Get AQI (دریافت AQI)")
        print("3. Get temperature (دریافت دما)")
        print("4. Get humidity (دریافت رطوبت)")
        print("5. Audio output (خروجی صوتی)")
        print("6. Change city (تغییر شهر)")
        print("0. Exit (خروج)")

        choice = input("Enter option: (🔹 گزینه را وارد کنید:) ")
        if choice == "1":
            aq.p("full")
        elif choice == "2":
            aq.p("aqi")
        elif choice == "3":
            aq.p("temperature")
        elif choice == "4":
            aq.p("humidity")
        elif choice == "5":
            aq.speak_info()
        elif choice == "6":
            return terminal_mode()
        elif choice == "0":
            print("Goodbye! (👋 خداحافظ!)")
            break
        else:
            print("Invalid option. Try again. (❌ گزینه نامعتبر. دوباره امتحان کنید.)")








