﻿# -*- coding: utf-8 -*-
"""
FikaSPT Versions Monitor — JSON Generator + Discord Notifier
Scans this directory for SPT-*.zip archives,
writes versions.json for client sync,
and posts a one-time Discord notification when a new version appears.
Uses only built-in Python + curl.
"""

import os
import re
import json
import subprocess
import base64
from datetime import datetime


# -------------------------------
# Simple version parser
# -------------------------------
def parse_version(v):
    """Convert '4.0.3' → (4,0,3) safely."""
    try:
        return tuple(int(x) for x in v.split("."))
    except:
        return (0,)


# -------------------------------
# CONFIGURATION
# -------------------------------
FOLDER = "/mnt/user/appdata/webserver-php8.4/html/downloads/SPTVersions"
BASE_URL = "https://files.vmvproductions.net/downloads/SPTVersions"
OUTPUT_FILE = os.path.join(FOLDER, "versions.json")
LAST_FILE = os.path.join(FOLDER, "fika_spt_last_version.txt")
DISCORD_WEBHOOK_URL = "https://discord.com/api/webhooks/1442596351928963250/SPKhZQCImiSD1njA4yhw2l1lmERGPEkAi_cXi-KVcvm6gWHH1gC_N6xSGFMJaPPsTbxJ"

LOG_DIR = os.path.join(FOLDER, "logs")
LOG_FILE = os.path.join(LOG_DIR, "versions_monitor.log")

# Allowed archive filename format:
pattern = re.compile(r"^SPT-(\d+(?:\.\d+)+).*\.zip$", re.IGNORECASE)

os.makedirs(LOG_DIR, exist_ok=True)


# -------------------------------
# LOGGING
# -------------------------------
def log(msg):
    ts = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
    line = f"{ts} {msg}"
    print(line)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(line + "\n")


# -------------------------------
# DISCORD WEBHOOK (curl)
# -------------------------------
def send_discord_message(message):
    """Send message to Discord webhook using curl."""
    payload = json.dumps({"content": message})
    payload_b64 = base64.b64encode(payload.encode()).decode()

    cmd = [
        "bash",
        "-c",
        f'echo "{payload_b64}" | base64 -d | '
        f'curl -s -H "Content-Type: application/json" -X POST -d @- "{DISCORD_WEBHOOK_URL}"'
    ]

    try:
        subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        log("📤 Posted new version notice to Discord.")
    except subprocess.CalledProcessError as e:
        stderr_text = e.stderr.decode(errors="ignore") if e.stderr else str(e)
        log(f"⚠️ Discord post failed: {stderr_text}")


# -------------------------------
# MAIN LOGIC
# -------------------------------
def main():
    log("🚀 Running FikaSPT version monitor...")

    # Find all SPT-*.zip
    archives = []
    for name in os.listdir(FOLDER):
        m = pattern.match(name)
        if not m:
            continue

        version = m.group(1)
        archives.append({
            "filename": name,
            "version": version,
            "url": f"{BASE_URL}/{name}"
        })

    if not archives:
        log("⚠️ No valid SPT archives found.")
        return

    # Sort NEWEST first
    archives.sort(key=lambda x: parse_version(x["version"]), reverse=True)
    latest = archives[0]["version"]

    # Write versions.json
    data = {"latest_version": latest, "archives": archives}
    with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)

    log(f"📄 versions.json updated ({len(archives)} archives, latest = {latest})")

    # Check last known version
    previous = None
    if os.path.exists(LAST_FILE):
        with open(LAST_FILE, "r", encoding="utf-8") as f:
            previous = f.read().strip()

    if previous != latest:
        log(f"🚀 New version detected: {latest} (previous: {previous})")
        with open(LAST_FILE, "w", encoding="utf-8") as f:
            f.write(latest)

        message = (
            f"🚀 **New SPT version uploaded!**\n"
            f"**Version:** {latest}\n"
            f"✅ Make sure to run your SPT Updater to join the server!!"
        )


        send_discord_message(message)
    else:
        log(f"✔️ No new version (still {latest}).")

    log("✅ Done.\n" + "-" * 60)


# -------------------------------
# ENTRY
# -------------------------------
if __name__ == "__main__":
    main()
