"""Bounded ptunnel profile management; never touches unrelated client tunnels."""
import json
from pathlib import Path
import subprocess
from urllib.parse import urlsplit

from .mask_model_training_data import PROJECT,require

PTUNNEL=Path('/root/.local/bin/ptunnel')
MIGRATION=PROJECT/'outputs/pallet_description_round5_ptunnel_v1'


def profile_name(mode):
    require(mode in ('new','existing'),'Unknown review mode')
    return 'pallet-description-round5-'+mode


def validate_route(row,*,mode,port):
    require(isinstance(row,dict) and row.get('id')==profile_name(mode),'Wrong ptunnel local profile')
    require(row.get('type')=='http' and row.get('host')=='127.0.0.1' and row.get('port')==port and row.get('target')==f'127.0.0.1:{port}','Unexpected ptunnel upstream')
    url=row.get('url');parsed=urlsplit(url or '')
    require(parsed.scheme=='https' and parsed.hostname and parsed.hostname.endswith('.tunnel.phineas.top') and not parsed.username and not parsed.password and not parsed.port
        and parsed.path in ('','/') and not parsed.query and not parsed.fragment,'Unexpected public ptunnel URL')
    return row


def command(args,timeout=30):
    result=subprocess.run([str(PTUNNEL),*args],check=True,capture_output=True,text=True,timeout=timeout)
    return json.loads(result.stdout)


def profiles():
    rows=command(['list','--json']);require(isinstance(rows,list),'Unexpected ptunnel inventory response')
    require(all(isinstance(r,dict) and isinstance(r.get('id'),str) for r in rows),'Invalid profile inventory')
    require(len({r['id'] for r in rows})==len(rows),'Duplicate ptunnel profiles')
    return {row['id']:row for row in rows}


def ensure_route(mode,port):
    name=profile_name(mode);rows=profiles()
    if name in rows:
        row=validate_route(rows[name],mode=mode,port=port)
        # Do not duplicate or delete a pending/reconnecting saved profile. The
        # existing daemon owns bounded backoff and reconnects its own worker.
        require(row.get('status')=='connected','Saved ptunnel profile is reconnecting; inspect existing profile, do not recreate')
        return row
    return validate_route(command(['http',str(port),'--host','127.0.0.1','--name',name,'--json'],timeout=260),mode=mode,port=port)
