import os
import json
import time
import datetime
import requests

SCHEDULE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "roadmap_vote_schedule.json")
THREAD_ID = "1554350976146739274"
WEBHOOK_URL = f"https://discord.com/api/webhooks/1554337516298174514/fRIZSc20O2bRiETvt9nncPLhAWEUQbb3_gPXFUVy4WjHtrAFnXTkDnRmEIgfHDY4f0Og?thread_id={THREAD_ID}"

ASF_IPC_URL = "http://23.128.44.171:1242/Api/Command"
ASF_PASSWORD = "DHyBE0vNjdaOE594tBpLm4SS"

def load_schedule():
    if not os.path.exists(SCHEDULE_FILE):
        return []
    with open(SCHEDULE_FILE, "r", encoding="utf-8") as f:
        return json.load(f)

def save_schedule(queue):
    with open(SCHEDULE_FILE, "w", encoding="utf-8") as f:
        json.dump(queue, f, indent=2)

def execute_vote(job):
    bot_name = job["bot"]
    feature_name = job["feature_name"]
    print(f"[{datetime.datetime.now(datetime.timezone.utc).strftime('%H:%M:%S')}] Executing scheduled vote: {bot_name} -> {feature_name}")

    # Dispatch to ASF IPC
    headers = {
        "Authentication": ASF_PASSWORD,
        "Content-Type": "application/json"
    }
    # Command to ASF SboxPlugin
    cmd = f"sbox fav {bot_name} facepunch.{job['feature_id']} true"
    try:
        r = requests.post(ASF_IPC_URL, headers=headers, json={"Command": cmd}, timeout=10)
        asf_res = r.json().get("Result", "OK") if r.status_code == 200 else f"HTTP {r.status_code}"
    except Exception as ex:
        asf_res = f"Error: {ex}"

    job["status"] = "EXECUTED"
    job["executed_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
    job["asf_result"] = asf_res
    return True

def run_due_votes():
    queue = load_schedule()
    now_iso = datetime.datetime.now(datetime.timezone.utc).isoformat()

    executed_count = 0
    for job in queue:
        if job["status"] == "SCHEDULED" and job["scheduled_time"] <= now_iso:
            execute_vote(job)
            executed_count += 1
            time.sleep(2) # Micro-spacing between simultaneous dues

    if executed_count > 0:
        save_schedule(queue)
        print(f"Executed {executed_count} due votes.")
    else:
        pending = sum(1 for j in queue if j["status"] == "SCHEDULED")
        print(f"No votes due right now. ({pending} votes pending in 5m-12h queue)")

if __name__ == "__main__":
    run_due_votes()
