#!/usr/bin/python3
"""Normal user commands; protocol and confinement remain in the unchanged helper."""
import argparse, contextlib, importlib.util, io, json, os, pathlib, subprocess, sys, hashlib, html, stat
BASE=pathlib.Path(os.environ.get('TESI_CONNECT_PACKAGE_DIR','/usr/lib/tesi-this-computer'))
# The pinned helper (connect.py) is shared with the stand-alone download, whose flags are --reconnect/--pair/--install.
# Packaged users have subcommands instead, so its hints are rewritten here.
HINTS=(('Use --reconnect.','Use tesi-connect resume.'),
 ('Use --pair after installing the user helper.','Run tesi-connect pair to connect it again.'),
 ('Choose a folder first: --install --folder /absolute/path','Choose a folder first: run tesi-connect setup.'))
def packaged_text(text):
 for old,new in HINTS:text=text.replace(old,new)
 return text
# Operator-configured per-user relay origin (2.1.9): ~/.config/tesi-connect/origin (XDG_CONFIG_HOME honoured).
# Precedence: explicit TESI_CONNECT_ORIGIN, then this private file, then the ordinary customer default.
DEFAULT_ORIGIN='https://toolsenabled.ai'
ORIGIN_SOURCE='default'
class OriginConfigError(RuntimeError):pass
def origin_file():
 return pathlib.Path(os.environ.get('XDG_CONFIG_HOME') or str(pathlib.Path.home()/'.config'))/'tesi-connect'/'origin'
def valid_origin(text):
 import urllib.parse
 value=text.strip()
 if not value or len(value)>255 or any(c.isspace() for c in value):raise OriginConfigError('The TESI address in '+str(origin_file())+' is not a single web address.')
 u=urllib.parse.urlsplit(value)
 if u.username or u.password or u.path not in ('','/') or u.query or u.fragment or not u.hostname or not (u.scheme=='https' or u.scheme=='http' and u.hostname in ('127.0.0.1','localhost','::1')):
  raise OriginConfigError('The TESI address in '+str(origin_file())+' must be https://host[:port] (http only for this computer).')
 try:u.port
 except ValueError:raise OriginConfigError('The TESI address in '+str(origin_file())+' has an invalid port.')
 return u.scheme+'://'+u.netloc
def read_origin_file(path):
 uid=os.geteuid()
 try:parent=os.lstat(path.parent)
 except OSError as error:raise OriginConfigError('The TESI address folder '+str(path.parent)+' cannot be read.') from error
 if not stat.S_ISDIR(parent.st_mode) or parent.st_uid not in (uid,0) or parent.st_mode&0o022:
  raise OriginConfigError('The TESI address folder '+str(path.parent)+' must be a real folder owned by you and not writable by others.')
 info=os.lstat(path)
 if stat.S_ISLNK(info.st_mode):raise OriginConfigError('The TESI address file '+str(path)+' is a link; it must be a regular private file.')
 try:fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK)
 except OSError as error:raise OriginConfigError('The TESI address file '+str(path)+' cannot be opened.') from error
 try:
  st=os.fstat(fd)
  if not stat.S_ISREG(st.st_mode) or (st.st_dev,st.st_ino)!=(info.st_dev,info.st_ino):raise OriginConfigError('The TESI address file '+str(path)+' must be a regular private file.')
  if st.st_uid!=uid:raise OriginConfigError('The TESI address file '+str(path)+' is not owned by you; it was not used.')
  if st.st_mode&0o077:raise OriginConfigError('The TESI address file '+str(path)+' must be private (chmod 600); it was not used.')
  if st.st_size>512:raise OriginConfigError('The TESI address file '+str(path)+' is too large.')
  data=os.read(fd,513).decode('utf-8','strict')
 except UnicodeDecodeError as error:raise OriginConfigError('The TESI address file '+str(path)+' is not text.') from error
 finally:os.close(fd)
 return valid_origin(data)
def configure_origin():
 global ORIGIN_SOURCE
 if os.environ.get('TESI_CONNECT_ORIGIN'):ORIGIN_SOURCE='environment';return ORIGIN_SOURCE
 path=origin_file()
 try:os.lstat(path)
 except FileNotFoundError:ORIGIN_SOURCE='default';return ORIGIN_SOURCE
 os.environ['TESI_CONNECT_ORIGIN']=read_origin_file(path);ORIGIN_SOURCE='file';return ORIGIN_SOURCE
def check_binding(h):
 # A saved pairing or folder choice made for one TESI address is never silently used against another.
 origin=h.ORIGIN.rstrip('/')
 # Only an origin the saved file actually records is compared (the helper keeps its own rule for older grants).
 for name,label,fallback in (('device.json','pairing',None),('scope.json','folder choice',None)):
  try:saved=json.loads((pathlib.Path(h.state_dir())/name).read_text())
  except (OSError,ValueError):continue
  value=saved.get('origin',fallback) if isinstance(saved,dict) else None
  if value is not None and str(value).rstrip('/')!=origin:
   where={'file':str(origin_file()),'environment':'TESI_CONNECT_ORIGIN','default':'the default'}[ORIGIN_SOURCE]
   raise OriginConfigError('This computer\'s saved '+label+' belongs to '+str(value).rstrip('/')+', but the TESI address in use is '+origin+' (from '+where+'). Nothing was changed; correct the address or pair again with a fresh private state.')

def run_helper(fn,*args):
 buffer=io.StringIO()
 try:
  with contextlib.redirect_stdout(buffer):return fn(*args)
 finally:
  sys.stdout.write(packaged_text(buffer.getvalue()));sys.stdout.flush()
def load():
 spec=importlib.util.spec_from_file_location('tesi_helper',BASE/'connect.py'); h=importlib.util.module_from_spec(spec);spec.loader.exec_module(h)
 origin=h.urllib.parse.urlsplit(h.ORIGIN)
 if origin.username or origin.password or origin.path not in ('','/') or origin.query or origin.fragment or not (origin.scheme=='https' or origin.scheme=='http' and origin.hostname in ('127.0.0.1','localhost','::1')):raise RuntimeError('A secure service origin is required.')
 manifest=json.loads((BASE/'assets.json').read_text())
 for name,digest in manifest['pins'].items():
  if hashlib.sha256((BASE/name).read_bytes()).hexdigest()!=digest:raise RuntimeError('Installed package asset changed; reinstall the package.')
 original=h.request_json; opener=h.HTTP
 class Assets:
  def open(self,url,**kw):
   target = url.full_url if isinstance(url, h.urllib.request.Request) else url
   path=target.removeprefix(h.ORIGIN)
   if target.startswith(h.ORIGIN) and path in manifest['paths']:return io.BytesIO((BASE/manifest['paths'][path]).read_bytes())
   return opener.open(url,**kw)
 h.HTTP=Assets()
 def request(method,url,*a,**kw):
  if method=='GET' and url==h.ORIGIN+'/api/connect/helper':return 200,manifest['metadata']
  return original(method,url,*a,**kw)
 h.request_json=request
 original_work=h.ensure_work
 def ensure_installed_work(folder,allow=False):
  if not allow:
   try:
    consent=json.loads((pathlib.Path(h.state_dir())/'work.json').read_text())
   except FileNotFoundError:
    return
   if (consent.get('allowed') is not True or consent.get('origin')!=h.ORIGIN.rstrip('/')
       or consent.get('folder')!=folder or not h.saved_grant()):
    return
   if consent.get('pinDigest')==manifest['metadata']['work']['pinDigest']:
    return
  original_work(folder,True)
 h.ensure_work=ensure_installed_work
 return h

class UserManagerError(RuntimeError):pass

def actionable_setup_detail(error):
 if isinstance(error,(UserManagerError,OriginConfigError)):return str(error)
 text=str(error)
 if text in (
  'Saved work consent belongs to another folder or service. Keep that folder or choose a fresh private state explicitly.',
  'Pairing was not approved; no service started.',
 ):
  return text
 return ''

def manager_environment():
 uid=os.geteuid()
 if uid==0 or os.getuid()!=uid:raise UserManagerError('Run service commands as the native desktop user, without sudo.')
 runtime=pathlib.Path('/run/user')/str(uid)
 # Caller XDG/DBUS values may name a private application bus. Only the native
 # per-UID runtime hierarchy and its owned socket select the manager.
 for path,owner,private in [(pathlib.Path('/run'),0,False),(runtime.parent,0,False),(runtime,uid,True)]:
  try:info=path.lstat()
  except OSError as error:raise UserManagerError('Native systemd user manager runtime is unavailable.') from error
  if not stat.S_ISDIR(info.st_mode) or info.st_uid!=owner or info.st_mode & (0o077 if private else 0o022):
   raise UserManagerError('Native systemd user manager runtime is not trusted.')
 try:info=(runtime/'bus').lstat()
 except OSError as error:raise UserManagerError('Native systemd user manager bus is unavailable.') from error
 if not stat.S_ISSOCK(info.st_mode) or info.st_uid!=uid:
  raise UserManagerError('Native systemd user manager bus is not trusted.')
 env=dict(os.environ)
 env['XDG_RUNTIME_DIR']=str(runtime)
 env['DBUS_SESSION_BUS_ADDRESS']='unix:path='+str(runtime/'bus')
 return env

def service(*args):
 env=manager_environment()
 # A socket alone can be stale or host a different bus. Ask the native manager
 # before effects; both the probe and action must succeed.
 try:probe=subprocess.run(['systemctl','--user','show','--property=Version','--value'],env=env,check=True,capture_output=True,text=True)
 except (OSError,subprocess.CalledProcessError) as error:raise UserManagerError('Native systemd user manager is unavailable or could not be identified.') from error
 if not probe.stdout.strip():raise UserManagerError('Native systemd user manager could not be identified.')
 if not args:return  # probe only
 subprocess.run(['systemctl','--user',*args],env=env,check=True)

def configure(h,a):
 # Refuse before any website claim or saved consent when the per-user service cannot run,
 # so the account never shows a computer that was approved but can never start.
 service()
 saved=pathlib.Path(h.state_dir())/'work.json'
 if saved.exists():
  cfg=json.loads(saved.read_text())
  if cfg.get('allowed') and ((a.folder is not None and cfg.get('folder')!=os.path.realpath(a.folder)) or cfg.get('origin')!=h.ORIGIN.rstrip('/')):raise RuntimeError('Saved work consent belongs to another folder or service. Keep that folder or choose a fresh private state explicitly.')
 folder=h.choose_folder(a.folder)
 h.ensure_work(folder,a.allow_work)
 grant=h.saved_grant()
 if a.command=='pair' and grant:
  code,body=h.request_json('GET',h.ORIGIN+'/api/connect/device/status',headers={'authorization':'Device '+grant['deviceToken']})
  if code==401:
   import time
   os.replace(os.path.join(h.state_dir(),'device.json'),os.path.join(h.state_dir(),'device.revoked-%d.json'%time.time_ns()))
  elif code!=200 or body.get('active') is not True:raise RuntimeError('Existing credential status is unknown; saved identity is retained.')
 if not h.saved_grant():
  ticket=h.begin_pairing(True);print('Approve this computer on the signed-in website. Code: '+ticket['code'],flush=True)
  # Desktop setup has no terminal: show the code and address while waiting.
  waiting=None
  if getattr(a,'desktop',False):
   try:waiting=subprocess.Popen(['zenity','--info','--no-wrap','--title=TESI Connect','--text=Approve this computer on the signed-in TESI website. Your browser was asked to open it; otherwise open '+html.escape(getattr(h,'PAGE_ORIGIN',h.ORIGIN).rstrip('/')+'/connect/')+' and enter\n\nCode: '+html.escape(ticket['code'])+'\n\nThis window closes after you approve.'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
   except OSError:waiting=None
  try:outcome=h.wait_for_grant(ticket)
  finally:
   if waiting is not None and waiting.poll() is None:waiting.terminate()
  if outcome!='granted':raise RuntimeError('Pairing was not approved; no service started.')
  # A new approval is an explicit request to connect: clear an earlier local disconnect/pause.
  h.control('connected')
 h.ensure_runtime()
 h.private_write(os.path.join(h.state_dir(),'helper.py'),(BASE/'connect.py').read_text())
 unit_dir=pathlib.Path(os.environ.get('XDG_CONFIG_HOME',str(pathlib.Path.home()/'.config')))/'systemd/user';unit_dir.mkdir(parents=True,exist_ok=True)
 quote=lambda v:json.dumps(str(v).replace('%','%%'),ensure_ascii=False)
 unit='[Unit]\nDescription=TESI connected computer\nAfter=network-online.target\n[Service]\nType=exec\nExecStart='+quote(pathlib.Path(__file__).resolve())+' work\nEnvironment='+quote('TESI_CONNECT_STATE_DIR='+h.state_dir())+(('\nEnvironment='+quote('TESI_CONNECT_ORIGIN='+h.ORIGIN)) if ORIGIN_SOURCE=='environment' else '')+'\nRestart=on-failure\nRestartSec=5\nRestartPreventExitStatus=2\nUMask=0077\n[Install]\nWantedBy=default.target\n'
 h.private_write(str(unit_dir/h.UNIT),unit)
 service('daemon-reload');service('enable',h.UNIT)
 service('restart',h.UNIT);service('is-active','--quiet',h.UNIT)
 print('Connected. The helper reconnects at login. Use tesi-connect status, pause or disconnect.');return 0
def dialog(*args):
 r=subprocess.run(['zenity',*args],capture_output=True,text=True)
 if r.returncode==1:return None
 if r.returncode!=0:raise RuntimeError('The desktop dialog could not open.')
 return r.stdout.rstrip('\n')

def service_healthy(h):
 # True only when the per-user unit is installed AND active, so an ordinary reopen can show status
 # without touching it. A missing or inactive unit, or an unreachable manager, is a real repair and is
 # allowed to re-enable/restart. Goes through service() (is-active is read-only) so the probe stays mocked.
 unit_dir=pathlib.Path(os.environ.get('XDG_CONFIG_HOME',str(pathlib.Path.home()/'.config')))/'systemd/user'
 if not (unit_dir/h.UNIT).exists():return False
 try:
  service('is-active','--quiet',h.UNIT)
  return True
 except (UserManagerError,subprocess.CalledProcessError,OSError):
  return False

def reopen_status(h):
 # Reopening an already set-up computer must change nothing: never daemon-reload/enable/restart (that
 # interrupts a running job) and never override an explicit local pause or disconnect. Show the real state.
 try:mode=json.loads((pathlib.Path(h.state_dir())/'control.json').read_text()).get('mode','connected')
 except (OSError,ValueError):mode='connected'
 folder='(saved)'
 try:folder=json.loads((pathlib.Path(h.state_dir())/'scope.json').read_text()).get('folder') or folder
 except (OSError,ValueError):pass
 grant=h.saved_grant();web=None
 try:
  if grant:
   code,body=h.request_json('GET',h.ORIGIN+'/api/connect/device/status',headers={'authorization':'Device '+grant['deviceToken']})
   if code==200 and isinstance(body,dict):web=body
 except (OSError,ValueError):web=None
 if mode=='disconnected':line='This computer is disconnected from TESI (you disconnected it here). Your pairing and folder are saved. Use tesi-connect resume to connect it again.'
 elif mode=='paused':line='TESI requests are paused on this computer. Use tesi-connect resume to allow them again.'
 elif web is not None and web.get('connected') and web.get('paused'):line='Connected to TESI and paused. Use tesi-connect resume.'
 elif web is not None and web.get('connected'):line='Connected to TESI. The helper reconnects at login; nothing was changed.'
 else:line='Set up; the helper reconnects to TESI automatically. Nothing was changed.'
 line+=' Folder: '+str(folder)+'. Use tesi-connect status, pause, resume or disconnect.'
 print(line,flush=True)
 dialog('--info','--title=TESI Connect','--text='+html.escape(line))
 return 0

def setup(h):
 saved=pathlib.Path(h.state_dir())/'scope.json'
 folder=None;allow=False
 if saved.exists():
  cfg=json.loads(saved.read_text())
  if cfg.get('origin')!=h.ORIGIN.rstrip('/'):raise RuntimeError('Saved scope belongs to another service.')
  # Ordinary reopen: already paired and the service is healthy -> status only, no restart, no re-enable.
  # Fall through to configure only for a real repair (unit missing/inactive) or re-pair (grant revoked).
  if h.saved_grant() and service_healthy(h):return reopen_status(h)
 else:
  folder=dialog('--file-selection','--directory','--title=TESI Connect — Choose a folder')
  if folder is None:return 0
  choice=dialog('--list','--radiolist','--title=TESI Connect','--text=TESI may read and change files in '+html.escape(folder)+'. Allowing work also lets native workers use this folder under Linux confinement and your TESI allowance. Confirm this computer on the signed-in website next.','--column=Choose','--column=Access','--print-column=2','--ok-label=Connect','FALSE','Allow work','TRUE','Files only')
  if choice is None:return 0
  if choice not in ('Allow work','Files only'):raise RuntimeError('Choose an access option.')
  allow=choice=='Allow work'
 try:
  result=configure(h,argparse.Namespace(command='install',folder=folder,allow_work=allow,desktop=True))
 except (RuntimeError,OSError,ValueError,subprocess.CalledProcessError) as error:
  extra=actionable_setup_detail(error)
  detail=(' '+extra) if extra else ''
  dialog('--error','--title=TESI Connect','--text=Setup could not finish. Your saved connection and consent are retained. Check the website connection, chosen folder and user service; use tesi-connect status for the current status.'+detail)
  return 2
 dialog('--info','--title=TESI Connect','--text=The helper is running and reconnects at login. Your folder and access choice are saved. Use tesi-connect status, pause, resume or disconnect to control it.')
 return result

def main():
 p=argparse.ArgumentParser(description='Connect one folder to TESI. Run as yourself; approve the code on the signed-in website.')
 p.add_argument('command',nargs='?',default='setup',choices=['setup','help','pair','install','work','status','pause','resume','reconnect','disconnect'])
 p.add_argument('--folder',help='Folder to share (asked on first setup)')
 p.add_argument('--allow-work',action='store_true',help='Explicitly allow native work in this folder using your TESI allowance')
 a=p.parse_args()
 if a.command=='help':p.print_help();print('Start: open TESI Connect from your application menu, or run tesi-connect setup.\nAdvanced: tesi-connect pair --folder /path/to/project --allow-work\nThen: tesi-connect status | pause | resume | disconnect');return 0
 if os.geteuid()==0:raise RuntimeError('Run tesi-connect as yourself, without sudo.')
 os.environ.setdefault('TESI_CONNECT_STATE_DIR',str(pathlib.Path(os.environ.get('XDG_STATE_HOME',str(pathlib.Path.home()/'.local/state')))/'tesi-connect'))
 configure_origin()  # explicit env, else the private origin file, else the ordinary default (2.1.9)
 h=load()
 check_binding(h)
 if a.command=='setup':return setup(h)
 if a.command in ('pair','install'):return configure(h,a)
 if a.command=='work':return h.serve()
 if a.command=='status':
  if ORIGIN_SOURCE=='file':print('TESI address: '+h.ORIGIN.rstrip('/')+' (from '+str(origin_file())+')')
  return run_helper(h.status)
 if a.command in ('pause','resume','reconnect','disconnect'):
  h.control({'pause':'paused','disconnect':'disconnected'}.get(a.command,'connected'))
  if a.command in ('resume','reconnect'):service('restart',h.UNIT);service('is-active','--quiet',h.UNIT)
  if a.command=='disconnect':
   print('Locally disconnected; saved identity and history retained. Website Disconnect revokes this credential.')
   try:
    grant=h.saved_grant();code,body=h.request_json('GET',h.ORIGIN+'/api/connect/device/status',headers={'authorization':'Device '+grant['deviceToken']}) if grant else (0,{})
   except (OSError,ValueError):code,body=0,{}
   print('Website refuses this credential.' if code==401 else 'Website still accepts this credential; use Disconnect there to revoke it.' if code==200 and body.get('active') is True else 'Server revocation status could not be checked.')
  return 0
def run_command():
 try:sys.exit(main())
 except (RuntimeError,OSError,ValueError,subprocess.CalledProcessError) as e:
  extra=actionable_setup_detail(e)
  if extra:print('tesi-connect: '+extra,file=sys.stderr)
  print('tesi-connect: setup or control failed; check your folder, private package/state and user service. No service success is assumed.',file=sys.stderr);sys.exit(2)
if __name__=='__main__':
 run_command()
