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"
]

OUTPUT_PATH = "/home/vkkwgsxr/public_html/gold/latest_prices.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=20)

        data = json.loads(
            response.read().decode("utf-8")
        )

        print("API OK:", url)

        break

    except Exception as e:

        print("API ERROR:", e)

if not data:

    raise Exception("NO DATA RECEIVED")

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"),
        "time_en": obj.get("t_en"),
        "timestamp": obj.get("ts")
    }

result = {

    "ons_gold": item("ons"),
    "ons_silver": item("silver"),
    "ons_platinum": item("platinum"),
    "oil_opec": item("oil_opec"),

    "gold_18k": item("geram18"),
    "gold_24k": item("geram24"),
    "gold_second_hand": item("gold_mini_size"),

    "melted_gold": item("gold_futures"),
    "silver_999": item("silver_999"),
    "silver_925": item("silver_925"),

    "emami_coin": item("sekeb"),
    "bahar_coin": item("sekeb"),
    "half_coin": item("nim"),
    "quarter_coin": item("rob"),
    "gram_coin": item("gerami"),

    "usd": item("price_dollar_rl"),
    "harat_usd": item("afghan_usd"),
    "eur": item("price_eur"),
    "aed": item("price_aed"),
    "gbp": item("price_gbp"),
    "try": item("price_try"),

    "brl": item("price_brl"),
    "tjs": item("price_tjs"),

    "updated_at": datetime.now().isoformat()
}

with open(OUTPUT_PATH, "w", encoding="utf-8") as f:

    json.dump(
        result,
        f,
        ensure_ascii=False,
        indent=2
    )

print("DONE")