#!/usr/bin/env python3
"""Root-only administration; never prints secrets during status or health checks."""
import json
import os
from pathlib import Path
import subprocess
import sys
import urllib.request
SERVICES=['cortex-datastores','cortex-api','cortex-worker','cortex-watcher','cortex-dashboard','cortex-rag-refresh.timer']
if os.geteuid()!=0:sys.exit('Run with sudo: sudo cortexctl '+(sys.argv[1] if len(sys.argv)>1 else 'status'))
values={}
for line in Path('/opt/memory-cortex/.env').read_text().splitlines():
    key,sep,value=line.partition('=')
    if sep:values[key]=value
command=sys.argv[1] if len(sys.argv)>1 else 'status'
if command=='status':sys.exit(subprocess.call(['systemctl','--no-pager','status',*SERVICES]))
elif command=='health':
    req=urllib.request.Request('http://127.0.0.1:8088/ready',headers={'X-API-Key':values['MEMORY_CORTEX_READ_API_KEY']})
    try:
        with urllib.request.urlopen(req,timeout=15) as response:print(json.dumps(json.load(response),indent=2))
    except OSError as error:sys.exit('Health check failed: '+str(error))
elif command=='credentials':
    print('Private credentials: keep these out of chat, logs and shared files.')
    for key in ['MEMORY_CORTEX_READ_API_KEY','MEMORY_CORTEX_WRITE_API_KEY','MEMORY_CORTEX_ADMIN_API_KEY']:print(key+'='+values[key])
elif command in ('start','stop','restart'):
    if command in ('stop','restart'):
        subprocess.run(['systemctl','stop','cortex-rag-refresh.timer','cortex-rag-refresh.service'],check=True)
    ordered=SERVICES if command!='stop' else list(reversed(SERVICES))
    sys.exit(subprocess.call(['systemctl',command,*ordered]))
else:sys.exit('Usage: sudo cortexctl {status|health|credentials|start|stop|restart}')
