"""
DEV-ONLY script: generate a password reset token_hash for an existing user.

Usage:
    cd C:\\Dev\\Talk2CV\\backend
    .\\venv\\Scripts\\activate
    python scripts/generate_reset_token.py

Output: prints the recovery token_hash that can be used to test POST /auth/reset-password.
Requires the target user to exist in auth.users (created via signup or generate_confirm_token.py).
"""
import sys
from urllib.parse import urlparse, parse_qs

sys.path.insert(0, ".")

from app.core.supabase_client import supabase

TEST_EMAIL = "fatielharti57@gmail.com"


def main():
    print(f"=== Generating recovery link for: {TEST_EMAIL} ===")

    link_response = supabase.auth.admin.generate_link({
        "type": "recovery",
        "email": TEST_EMAIL,
    })

    action_link = link_response.properties.action_link
    print(f"  Action link: {action_link}")

    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", ["recovery"])[0]

    if not token_hash:
        print("\nERROR: Could not extract token_hash from action_link")
        print(f"Full URL parsed: {parsed}")
        sys.exit(1)

    new_password = "NewSecret456"

    print(f"\n=== READY TO TEST /auth/reset-password ===")
    print(f"  token_hash:   {token_hash}")
    print(f"  type:         {link_type}")
    print(f"  new password: {new_password}")
    print(f"\nPowerShell test command:")
    print(f"""
$body = @{{
    tokenHash = "{token_hash}"
    newPassword = "{new_password}"
}} | ConvertTo-Json

$response = Invoke-RestMethod -Uri "http://localhost:8000/auth/reset-password" -Method POST -ContentType "application/json" -Body $body
$response | Format-List
""")


if __name__ == "__main__":
    main()
