import os
import json
import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Load config
with open("cpanel_config.json") as f:
    config = json.load(f)

CPANEL_HOST = config["cpanel_host"]
CPANEL_USER = config["cpanel_user"]
API_TOKEN = config["cpanel_api_token"]

UPLOAD_URL = f"https://{CPANEL_HOST}:2083/execute/Fileman/upload_files"

IGNORE_FILES = {
    "cpanel_config.json",
    "Upload.py",
    "upload_to_cpanel.py"
}

for file_name in os.listdir("."):
    if not os.path.isfile(file_name):
        continue

    if file_name in IGNORE_FILES:
        continue

    print(f"\nUploading {file_name}...")

    with open(file_name, "rb") as f:
        files = {"file-0": f}
        data = {
            "dir": "public_html",   # safer than /public_html
            "overwrite": 1
        }

        headers = {
            "Authorization": f"cpanel {CPANEL_USER}:{API_TOKEN}"
        }

        try:
            r = requests.post(
                UPLOAD_URL,
                headers=headers,
                files=files,
                data=data,
                verify=False,
                timeout=60
            )
        except Exception as e:
            print(f"❌ Request failed: {e}")
            continue

        print("STATUS:", r.status_code)
        print("RAW RESPONSE:", r.text)

        try:
            resp = r.json()
        except Exception:
            print("❌ Response is not JSON")
            continue

        # cPanel usually uses "errors" not "error"
        if r.status_code == 200 and resp.get("status") == 1:
            print(f"✅ Uploaded {file_name}")
        else:
            errors = resp.get("errors") or resp.get("error") or resp
            print(f"❌ Failed {file_name}: {errors}")