import requests
from datetime import datetime

# statics
DHL_API_KEY = "YOUR_KEY_HERE"
DHL_API_URL = "https://api-eu.dhl.com/track/shipments"
SHIPMENT_NUM = "YOUR_SHIPMENT_NUMBER_HERE"
DC_WEBHOOK_URL = "YOUR_WEBHOOK_URL_HERE"

querystring = {'trackingNumber': SHIPMENT_NUM}
headers = {
    'DHL-API-Key': DHL_API_KEY,
    'Accept': "application/json",
    'Content-Type': "application/json"
}

def get_shipment_status():
    response = requests.get(DHL_API_URL, headers=headers, params=querystring)
    if response.status_code == 200:
        data = response.json()
        if "shipments" in data and len(data["shipments"]) > 0:
            return data["shipments"][0]["events"], data
    return None, None

def read_last_status():
    try:
        with open("/home/matteo/Scripts/last_status.txt", 'r') as file:
            status = file.read().strip()
            return status
    except FileNotFoundError:
        return None

def write_last_status(status):
    with open("/home/matteo/Scripts/last_status.txt", 'w') as file:
        file.write(status)

def send_discord_webhook(data):
    latest_event = max(data['shipments'][0]['events'], key=lambda x: x['timestamp'])
    
    description = latest_event['description']
    timestamp = datetime.strptime(latest_event['timestamp'], "%Y-%m-%dT%H:%M:%S").strftime("%H:%M:%S %d.%m.%Y")

    if latest_event['description'] == "":
        description = "*Keine Beschreibung verfügbar*"

    webhook_data = {
        "content": "<@933697808152801311>",
        "embeds": [
            {
                "title": "DHL Paket Tracking",
                "description": f"Neues Update für dein Paket",
                "color": 0x00ff00,
                "fields": [
                    {
                        "name": "Status Code",
                        "value": latest_event['statusCode']
                    },
                    {
                        "name": "Beschreibung",
                        "value": description
                    },
                    {
                        "name": "Ort",
                        "value": latest_event['location']['address']['addressLocality']
                    },
                    {
                        "name": "Voraussichtliches Lieferdatum",
                        "value": datetime.strptime(data['shipments'][0]['estimatedTimeOfDelivery'], "%Y-%m-%d").strftime("%d.%m.%Y")
                    }
                ],
                "footer": {
                    "text": f"Update von: {timestamp}"
                }
            }
        ]
    }
 
    headers = {
        "Content-Type": "application/json"
    }
    response = requests.post(DC_WEBHOOK_URL, json=webhook_data, headers=headers)
    if response.status_code == 204:
        print("Successfully sent webhook.")
    else:
        print(f"Failed to send webhook: {response.status_code}, {response.text}")

def main():
    events, data = get_shipment_status()
    if events is None:
        print("Failed to retrieve shipment status.")
        return

    latest_event = max(events, key=lambda x: x['timestamp'])
    current_status = latest_event['statusCode'].lower() + "+" + latest_event['timestamp']

    print(data)

    last_status = read_last_status()
    if current_status != last_status:
        print(f"Status changed from {last_status} to {current_status}")
        write_last_status(current_status)
        send_discord_webhook(data)
    else:
        print("Status unchanged.")

if __name__ == "__main__":
    main()
