import json
import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Load config
with open("cpanel_config.json", "r") as f:
    config = json.load(f)

CPANEL_HOST = config["cpanel_host"]
CPANEL_USER = config["cpanel_user"]
API_TOKEN = config["cpanel_api_token"]

HEADERS = {
    "Authorization": f"cpanel {CPANEL_USER}:{API_TOKEN}"
}

TARGET_DIR = "/public_html"

LIST_URL = f"https://{CPANEL_HOST}:2083/execute/Fileman/list_files"
DELETE_URL = f"https://{CPANEL_HOST}:2083/execute/Fileman/delete_file"

print("\nFetching files...\n")

r = requests.get(
    LIST_URL,
    headers=HEADERS,
    params={"dir": TARGET_DIR},
    verify=False,
    timeout=30
)

if r.status_code != 200:
    print("HTTP error:", r.status_code)
    print(r.text)
    exit()

data = r.json()

# ----------------------------
# DEBUG (uncomment if needed)
# ----------------------------
# import json
# print(json.dumps(data, indent=2))
# exit()

files = []

raw = data.get("data")

# Handle different API formats safely
if isinstance(raw, dict):
    raw = raw.get("files") or raw.get("items") or []

if not isinstance(raw, list):
    raw = []

for item in raw:
    if not isinstance(item, dict):
        continue

    filename = (
        item.get("name")
        or item.get("file")
        or item.get("filename")
        or item.get("basename")
    )

    if filename:
        files.append(filename)

# Remove duplicates + empty values
files = [f for f in files if f]

if not files:
    print("No files found (or API format mismatch).")
    print("Uncomment debug section to inspect response.")
    exit()

print("Files found:\n")

for i, f in enumerate(files, 1):
    print(f"{i}. {f}")

selection = input("\nSelect files to delete (e.g. 1,3,5): ").strip()

try:
    indexes = [int(x.strip()) - 1 for x in selection.split(",")]
except:
    print("Invalid input")
    exit()

to_delete = [files[i] for i in indexes if 0 <= i < len(files)]

if not to_delete:
    print("No valid selections")
    exit()

print("\nSelected:")
for f in to_delete:
    print("-", f)

confirm = input("\nType DELETE to permanently remove: ").strip()

if confirm != "DELETE":
    print("Cancelled")
    exit()

print("\nDeleting...\n")

for f in to_delete:
    path = f"{TARGET_DIR}/{f}"

    res = requests.post(
        DELETE_URL,
        headers=HEADERS,
        data={"sourcefiles": path},
        verify=False,
        timeout=30
    )

    if res.status_code == 200:
        print("Deleted:", f)
    else:
        print("Failed:", f, res.text)

print("\nDone.")