import os
import sys
import json
import argparse
import requests

# Set up argument parsing
parser = argparse.ArgumentParser(description="Test GraphQL ImportLeagueSetup mutation locally.")
parser.add_argument("filename", nargs="?", help="Name of the Excel file to upload.")
parser.add_argument("-t", "--token", default="clAv8xjO17iTxraosugaFcvxvB6jMOzm6BVBxQ0Fl4spCQLa3fgqQiMVayTc", help="Authentication token (X-Token).")
parser.add_argument("-o", "--org", default="myl_demo3_lms", help="Organisation database header (X-Organisation).")
args = parser.parse_args()

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
URL = "http://127.0.0.1:8000/"

# Resolve Excel filename
if args.filename:
    filename = args.filename
else:
    possible_names = ["league_setup_template.xlsx", "league_setup.xlsx"]
    filename = None
    for name in possible_names:
        if os.path.exists(os.path.join(BASE_DIR, name)):
            filename = name
            break
    if not filename:
        filename = "league_setup_template.xlsx"

EXCEL_PATH = os.path.join(BASE_DIR, filename)

if not os.path.exists(EXCEL_PATH):
    print("\n" + "="*50)
    print(f"ERROR: Excel file not found!")
    print(f"Tried looking for: {EXCEL_PATH} or {os.path.join(BASE_DIR, 'league_setup.xlsx')}")
    print("Please upload your Excel file to the folder or run:")
    print("  python test_import_excel.py <your_file_name.xlsx>")
    print("="*50 + "\n")
    sys.exit(1)

print(f"Uploading file: {EXCEL_PATH} to {URL}...")
print(f"Organisation: {args.org}")
print(f"Token: {args.token[:10]}...")

# GraphQL Multipart Request Payload
operations = {
    "query": "mutation ImportLeagueSetup($file: Upload!) { importLeagueSetup(file: $file) { success message } }",
    "variables": {
        "file": None
    }
}
map_data = {
    "my_excel": ["variables.file"]
}

# Target organization headers
headers = {
    "X-Organisation": args.org,
    "X-Token": args.token
}

with open(EXCEL_PATH, "rb") as f:
    files = {
        "operations": (None, json.dumps(operations), "application/json"),
        "map": (None, json.dumps(map_data), "application/json"),
        "my_excel": ("league_setup.xlsx", f, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    }
    
    try:
        response = requests.post(URL, headers=headers, files=files)
        print(f"\nStatus Code: {response.status_code}")
        print("Response Body:")
        print(json.dumps(response.json(), indent=2))
    except Exception as e:
        print(f"\nConnection Error: {e}")
