"""
DEV-ONLY script: generate a confirmation token_hash for an existing unconfirmed user.

Usage:
    cd C:\\Dev\\Talk2CV\\backend
    .\\venv\\Scripts\\activate
    python scripts/generate_confirm_token.py <email>

Output: prints the token_hash that can be used to test POST /auth/confirm.

Prerequisite: the user must already exist in auth.users with email_confirmed_at IS NULL
(typically: user just signed up via the app but hasn't clicked the email link yet).
"""
import sys
from urllib.parse import urlparse, parse_qs

# Make app importable from this script
sys.path.insert(0, ".")

from app.core.supabase_client import supabase  # admin client


def main():
    if len(sys.argv) < 2:
        print("ERROR: Email argument required.")
        print("Usage: python scripts/generate_confirm_token.py <email>")
        sys.exit(1)

    email = sys.argv[1].strip().lower()
    print(f"=== Generating confirmation link for: {email} ===")

    # Generate signup confirmation link for the existing user.
    # No password is needed when the user already exists with type=signup.
    link_response = supabase.auth.admin.generate_link({
        "type": "signup",
        "email": email,
    })

    action_link = link_response.properties.action_link
    print(f"  Action link: {action_link}")

    # Extract token_hash from URL query string
    parsed = urlparse(action_link)
    query = parse_qs(parsed.query)
    token_hash = query.get("token", [None])[0] or query.get("token_hash", [None])[0]
    link_type = query.get("type", ["signup"])[0]

    if not token_hash:
        print("\nERROR: Could not extract token_hash from action_link")
        print(f"Full URL parsed: {parsed}")
        sys.exit(1)

    print(f"\n=== READY TO TEST /auth/confirm ===")
    print(f"  token_hash: {token_hash}")
    print(f"  type:       {link_type}")
    print(f"\nDeeplink test command (PowerShell):")
    print(f'  adb -s <deviceId> shell am force-stop com.talk2cv')
    print(f'  adb -s <deviceId> shell am start -W -a android.intent.action.VIEW -d "talk2cv://email-confirm?token_hash={token_hash}&type={link_type}" com.talk2cv')
    print(f"\nHTTP test command (PowerShell, direct backend):")
    print(f"""
$body = @{{
    tokenHash = "{token_hash}"
    type = "{link_type}"
}} | ConvertTo-Json
$response = Invoke-RestMethod -Uri "http://localhost:8000/auth/confirm" -Method POST -ContentType "application/json" -Body $body
$response | Format-List
""")


if __name__ == "__main__":
    main()
