"""
Test the pure HTTP form POST approach for Microsoft auth.
"""
import requests
from bs4 import BeautifulSoup

session = requests.Session()
session.headers.update({
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
})

auth_url = "https://login.live.com/oauth20_authorize.srf?client_id=00000000402b5328&scope=service::user.auth.xboxlive.com::MBI_SSL&response_type=token&nocode=1"

def extract_form_data(soup):
    """Extract hidden fields and post URL from a Microsoft login form."""
    for form in soup.find_all('form'):
        action = form.get('action', '')
        if 'post.srf' in action or form.get('name') == 'f1' or form.get('id') == 'i0281':
            post_url = action
            if post_url and not post_url.startswith('http'):
                post_url = f"https://login.live.com{post_url}"
            fields = {}
            for inp in form.find_all('input'):
                name = inp.get('name')
                value = inp.get('value', '')
                if name:
                    fields[name] = value
            return post_url, fields
    return None, {}

# Step 1: GET authorize page
print("Step 1: GET authorize page...")
resp = session.get(auth_url)
print(f"  Status: {resp.status_code}")
soup = BeautifulSoup(resp.text, 'html.parser')
post_url, hidden = extract_form_data(soup)
print(f"  Post URL: {post_url[:100] if post_url else 'NONE'}...")
print(f"  Hidden fields: {len(hidden)}")
print(f"  PPFT: {hidden.get('PPFT', 'NONE')[:20]}...")

# Step 2: POST email
print(f"\nStep 2: POST email...")
hidden['loginfmt'] = 'testuser@gmail.com'
resp2 = session.post(post_url, data=hidden, allow_redirects=False)
print(f"  Status: {resp2.status_code}")
loc = resp2.headers.get('Location', '')
print(f"  Location: {loc[:120]}")

# Follow redirect
if resp2.status_code in (302, 303) and loc:
    resp3 = session.get(loc, allow_redirects=True)
    soup3 = BeautifulSoup(resp3.text, 'html.parser')
    
    pw_input = soup3.find('input', {'type': 'password'})
    if pw_input:
        print(f"  ✓ Direct password page! name={pw_input.get('name')}")
    else:
        body_text = soup3.get_text()
        if 'Send code' in body_text or 'Verify' in body_text:
            print("  → Got verification page, trying LoginOptions=1 to get password flow")
            
            post_url3, hidden3 = extract_form_data(soup3)
            if post_url3:
                hidden3['loginfmt'] = 'testuser@gmail.com'
                hidden3['LoginOptions'] = '1'
                resp4 = session.post(post_url3, data=hidden3, allow_redirects=False)
                print(f"     Status: {resp4.status_code}")
                loc4 = resp4.headers.get('Location', '')
                print(f"     Location: {loc4[:120]}")
                
                if resp4.status_code in (302, 303) and loc4:
                    resp5 = session.get(loc4, allow_redirects=True)
                    soup5 = BeautifulSoup(resp5.text, 'html.parser')
                    pw_input2 = soup5.find('input', {'type': 'password'})
                    if pw_input2:
                        print(f"     ✓ GOT PASSWORD PAGE via LoginOptions=1!")
                        # Extract all fields from password form
                        post_url5, hidden5 = extract_form_data(soup5)
                        print(f"     Post URL: {post_url5[:80] if post_url5 else 'NONE'}")
                        print(f"     Fields: {len(hidden5)}")
                        for k, v in hidden5.items():
                            print(f"       {k}: {v[:30] if v else ''}...")
                    else:
                        print(f"     Body: {soup5.get_text()[:300]}")
            else:
                print("  → No form found on verification page")
        else:
            print(f"  Unexpected: {body_text[:200]}")

print("\n=== COOKIES ===")
for name, value in session.cookies.items():
    print(f"  {name}: {value[:40]}...")
