import urllib.parse
import os
from dotenv import load_dotenv

project_folder = os.path.expanduser('~/public_html/knickershop.com')
load_dotenv(os.path.join(project_folder, '.env'))

CLIENT_ID = os.getenv('TRUELAYER_CLIENT_ID')
# Force the 's' here just to be absolutely safe
REDIRECT_URI = "https://knickershop.com/callback"

# --- 1. SETUP (At the very top) ---
CLIENT_ID = 'sandbox-knickershopdev-1561f6'
REDIRECT_URI = 'https://knickershop.com/callback'

def application(environ, start_response):
    
    # --- 2. THE "CATCHER" (Check for returning users first) ---
    query_string = environ.get('QUERY_STRING', '')
    params = urllib.parse.parse_qs(query_string)

    if 'code' in params:
        auth_code = params['code'][0]
        status = '200 OK'
        response_headers = [('Content-type', 'text/html')]
        start_response(status, response_headers)
        return [f"<h1>Success!</h1><p>Bank Connected. Code: {auth_code[:15]}...</p>".encode('utf-8')]

    # --- 3. THE "SENDER" (Only runs if there is no 'code' in the URL) ---
    # Put your Scopes and URL building here!
    scopes = "info%20accounts%20balance%20cards%20transactions%20direct_debits%20standing_orders%20offline_access"
    providers = "uk-cs-mock%20uk-ob-all%20uk-oauth-all"

    auth_url = (
        f"https://auth.truelayer-sandbox.com/?response_type=code"
        f"&client_id={CLIENT_ID}"
        f"&scope={scopes}"
        f"&redirect_uri={REDIRECT_URI}"
        f"&providers={providers}"
    )

    status = '200 OK'
    response_headers = [('Content-type', 'text/html')]
    start_response(status, response_headers)
    
    return [f'<html><body><a href="{auth_url}" style="font-size:24px;">CONNECT YOUR BANK</a></body></html>'.encode('utf-8')]
