import pandas as pd
import requests
import os

mngdebug = True

class CurrencyValue:
    def __init__(self, amount, currency, rates):
        self.base_value = amount / rates[currency]
        self.rates = rates

    def __getattr__(self, name):
        if name in self.rates:
            return round(self.base_value * self.rates[name], 2)
        raise AttributeError(f"{name} is not supported. Check {self.excel_path} or internet connection")

class CurrencyManager:
    def __init__(self, excel_path="currencies.xlsx", force_update=False):
        self.excel_path = excel_path
        self.prices = {}
        self.rates = self._load_or_fetch_rates(force_update)

    def _load_or_fetch_rates(self, force_update):
        if os.path.exists(self.excel_path) and not force_update:
            if mngdebug:
                print(f"Loading courses from {self.excel_path}")
            df = pd.read_excel(self.excel_path)
            return dict(zip(df["Currency"], df["Rate"]))
        if mngdebug:
            print("File not found. Loading current rates from the API...")
        try:
            url = "https://open.er-api.com/v6/latest/USD"
            response = requests.get(url)
            data = response.json()
            
            if data["result"] == "success":
                rates = data["rates"]
                df = pd.DataFrame(list(rates.items()), columns=["Currency", "Rate"])
                df.to_excel(self.excel_path, index=False)
                if mngdebug:
                    print(f"File {self.excel_path} created successfully!")
                return rates
        except Exception as e:
            if mngdebug:
                print(f"API connection error: {e}. Using backup rates.")
            return {"USD": 1.0, "JPY": 158.33, "EUR": 0.86, "GBP": 0.75, "CNY": 6.91}

    def setp(self, name, amount, currency="USD"):
        self.prices[name] = CurrencyValue(amount, currency, self.rates)
        return self.prices[name]

    def __getattr__(self, name):
        if name in self.prices:
            return self.prices[name]
        raise AttributeError(f"Price {name} has not been set")