import urllib.request
import json
from datetime import datetime

API_URLS = [
    "https://call4.tgju.org/ajax.json",
    "https://call5.tgju.org/ajax.json",
    "https://call3.tgju.org/ajax.json",
    "https://call2.tgju.org/ajax.json",
    "https://call1.tgju.org/ajax.json"
]

data = None

for url in API_URLS:

    try:

        req = urllib.request.Request(
            url,
            headers={
                "User-Agent": "Mozilla/5.0",
                "X-Requested-With": "XMLHttpRequest",
                "Referer": "https://www.tgju.org/"
            }
        )

        response = urllib.request.urlopen(req, timeout=15)

        data = json.loads(
            response.read().decode("utf-8")
        )

        print(f"SUCCESS: {url}")

        break

    except Exception as e:

        print(f"ERROR: {url}")
        print(e)

if data:

    current = data.get("current", {})

    def item(key):

        obj = current.get(key, {})

        return {
            "price": obj.get("p"),
            "change_percent": obj.get("dp"),
            "direction": obj.get("dt"),
            "high": obj.get("h"),
            "low": obj.get("l"),
            "time": obj.get("t")
        }

    result = {

        # =========================
        # اونس جهانی
        # =========================

        "ons_gold": item("ons"),
        "ons_silver": item("silver"),
        "ons_platinum": item("platinum"),

        # =========================
        # طلا
        # =========================

        "gold_18k": item("geram18"),
        "gold_24k": item("geram24"),
        "gold_second_hand": item("gold_mini_size"),
        "silver_999": item("noghre"),
        "melted_gold": item("abshode"),

        # =========================
        # سکه
        # =========================

        "emami_coin": item("sekee"),
        "bahar_coin": item("sekeb"),
        "half_coin": item("nim"),
        "quarter_coin": item("rob"),
        "gram_coin": item("gerami"),

        # =========================
        # ارز
        # =========================

        "usd": item("price_dollar_rl"),
        "eur": item("price_eur"),
        "aed": item("price_aed"),
        "gbp": item("price_gbp"),
        "try": item("price_try"),

        # =========================
        # بروزرسانی
        # =========================

        "updated_at": datetime.now().isoformat()
    }

    output_path = "/home/vkkwgsxr/public_html/gold/latest_prices.json"

    with open(output_path, "w", encoding="utf-8") as f:

        json.dump(
            result,
            f,
            ensure_ascii=False,
            indent=2
        )

    print("DONE")
    print(output_path)

else:

    print("FAILED")