"""Local session and private Tailscale Serve access. The backend binds only to loopback."""
import json
import os
import secrets
import shutil
import subprocess
from http.cookies import SimpleCookie
from pathlib import Path
from urllib.parse import urlparse, unquote

SESSION_TOKEN = secrets.token_urlsafe(32)
TAILSCALE_HOST = ''
TAILSCALE_LOGIN = ''

def local_request(handler):
    expected = {f'127.0.0.1:{handler.server.server_port}', f'localhost:{handler.server.server_port}'}
    return (handler.client_address[0] in ('127.0.0.1','::1') and handler.headers.get('Host','').lower() in expected
            and not any(k.lower().startswith(('tailscale-', 'x-forwarded-')) or k.lower()=='forwarded' for k in handler.headers))

def tailscale_request(handler):
    return bool(TAILSCALE_HOST and TAILSCALE_LOGIN and handler.client_address[0] in ('127.0.0.1','::1')
        and handler.headers.get('Host','').lower() in (TAILSCALE_HOST, TAILSCALE_HOST+':443')
        and handler.headers.get('X-Forwarded-Proto') == 'https'
        and not handler.headers.get('Tailscale-Funnel-Request')
        and unquote(handler.headers.get('Tailscale-User-Login','')).casefold() == TAILSCALE_LOGIN.casefold())

def trusted_origin(handler, mutation=False):
    local = local_request(handler)
    if not local and not tailscale_request(handler): return False
    expected = ('http://' if local else 'https://') + handler.headers.get('Host','').lower()
    origin = handler.headers.get('Origin')
    if origin and origin != expected: return False
    site = handler.headers.get('Sec-Fetch-Site','')
    if site and site not in ('same-origin','none'):
        # Opening an external link to the app is allowed; cross-site API requests are not.
        return (not mutation and handler.command == 'GET'
                and not urlparse(handler.path).path.startswith('/api/')
                and handler.headers.get('Sec-Fetch-Mode') == 'navigate'
                and handler.headers.get('Sec-Fetch-Dest') == 'document' and not origin)
    return True

def authorized(handler):
    if not trusted_origin(handler, handler.command != 'GET'): return False
    if tailscale_request(handler): return True
    try:
        cookie = SimpleCookie(handler.headers.get('Cookie',''))
        supplied = cookie.get('fa_session')
        return supplied is not None and secrets.compare_digest(supplied.value, SESSION_TOKEN)
    except Exception: return False

def bootstrap(handler):
    return local_request(handler) and trusted_origin(handler) and not urlparse(handler.path).path.startswith('/api/')

def cookie_header():
    return f'fa_session={SESSION_TOKEN}; Path=/; HttpOnly; SameSite=Strict'

def configure_tailscale(port):
    """Reuse the owner's private Serve route, or add one only when the HTTPS root is unused."""
    global TAILSCALE_HOST, TAILSCALE_LOGIN
    TAILSCALE_HOST = TAILSCALE_LOGIN = ''
    candidates = [shutil.which('tailscale')] + [str(Path(root)/'Tailscale'/'tailscale.exe') for root in (os.environ.get('ProgramW6432','C:/Program Files'),os.environ.get('ProgramFiles','C:/Program Files'))]
    exe = next((path for path in candidates if path and Path(path).is_file()), 'tailscale')
    flags = {'creationflags':subprocess.CREATE_NO_WINDOW} if os.name=='nt' else {}
    def run(*args):
        return subprocess.run([exe,*args],capture_output=True,text=True,encoding='utf-8',timeout=30,check=True,**flags).stdout
    try:
        status = json.loads(run('status','--json'))
        if status.get('BackendState') != 'Running': return 'Phone access unavailable: sign in to Tailscale and restart the app.'
        own = status.get('Self',{})
        host = own.get('DNSName','').rstrip('.').lower()
        user = status.get('User',{}).get(str(own.get('UserID')), {})
        login = user.get('LoginName','')
        if not host or not login: return 'Phone access unavailable: Tailscale owner identity could not be verified.'
        config = json.loads(run('serve','status','--json') or '{}')
        site = host+':443'
        if config.get('AllowFunnel',{}).get(site): return 'Phone access disabled: this address has Funnel enabled. Use private Tailscale Serve.'
        route = config.get('Web',{}).get(site,{}).get('Handlers',{}).get('/')
        target = f'http://127.0.0.1:{port}'
        if route and route.get('Proxy') != target: return 'Phone access unavailable: the Tailscale HTTPS root is assigned to another service.'
        if not route:
            run('serve','--bg','--https=443',target)
            config = json.loads(run('serve','status','--json') or '{}')
            route = config.get('Web',{}).get(site,{}).get('Handlers',{}).get('/')
            if not route or route.get('Proxy') != target: return 'Phone access unavailable: private Serve route could not be verified.'
        TAILSCALE_HOST, TAILSCALE_LOGIN = host, login
        return f'Private phone address: https://{host}/matches (use the same Tailscale account as this PC).'
    except subprocess.TimeoutExpired:
        return 'Phone access unavailable: Tailscale took too long to respond. Start Tailscale, then restart the app.'
    except (OSError, ValueError, subprocess.SubprocessError):
        return 'Phone access unavailable: start Tailscale and restart the app. Desktop access remains available.'
