#!/usr/bin/env python3
# summary: Choose a paired computer for private AI.
"""Choose a paired computer for private AI over the encrypted fleet link. list, use ID, here, share on|off, serve models|chat."""
import importlib.machinery
import importlib.util
import json
import re
import runpy
import subprocess
import sys
import urllib.parse
import urllib.request
from pathlib import Path

sys.path.insert(0,str(Path(__file__).resolve().parent))
import starchaser_ai_config as config
from starchaser_ask_store import fleet_allowed, policy
from starchaser_ask_fleet_payload import chat_payload
from starchaser_ai_quality import blocked
CONF = Path.home() / '.config/starchaser/ai.json'


def link():
    loader=importlib.machinery.SourceFileLoader('ask_fleet_link',str(Path(__file__).resolve().with_name('starchaser-link')))
    spec=importlib.util.spec_from_loader(loader.name,loader)
    module=importlib.util.module_from_spec(spec); loader.exec_module(module)
    return module


def remote(endpoint, body=None, timeout=120):
    parsed=urllib.parse.urlsplit(endpoint)
    ident=parsed.netloc
    if not re.fullmatch(r'[A-Za-z0-9_-]{1,80}',ident): raise ValueError('Choose a paired computer.')
    l=link()
    peer=next((p for p in l.load_peers() if p['id'] == ident and p.get('role') not in ('helper','help-target')),None)
    if not peer: raise RuntimeError('That computer is no longer paired.')
    result=l.ssh_to(peer,'ai-chat' if body else 'ai-models',timeout=timeout,input=json.dumps(body) + '\n' if body else None)
    if result.returncode: raise RuntimeError("The paired computer couldn't answer. Turn on private AI sharing there and try again.")
    data=json.loads(result.stdout)
    data['_computer']=peer.get('name') or ident
    if data.get('error'): raise RuntimeError(data['error'])
    return data


def serve(verb):
    if policy() != 'all' or not fleet_allowed(config.read(CONF)):
        raise RuntimeError('Private AI sharing is off on this computer.')
    engine=runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-ask')))
    if verb == 'models': path, body = '/api/tags',None
    elif verb == 'chat':
        raw=sys.stdin.readline(262145)
        if len(raw)>262144: raise ValueError('The question is too large.')
        body=chat_payload(json.loads(raw))
        with engine['model_open'](urllib.request.Request('http://127.0.0.1:11434/api/tags'),timeout=3) as response: tags=json.load(response).get('models',[])
        local_names={m.get('name') for m in tags if not m.get('remote_host') and not m.get('remote_model') and not re.search(r'(?:-cloud|:cloud)$',m.get('name',''),re.I) and not blocked(m.get('name',''), m.get('digest',''))}
        if body['model'] not in local_names: raise ValueError('Choose a downloaded private model on that computer.')
        path='/api/chat'
    else: raise ValueError('Invalid private AI operation.')
    req=urllib.request.Request('http://127.0.0.1:11434'+path,data=json.dumps(body).encode() if body else None,headers={'Content-Type':'application/json'})
    with engine['model_open'](req,timeout=120) as response: result = json.load(response)
    if verb == 'models': result['models'] = [m for m in result.get('models', []) if not blocked(m.get('name',''), m.get('digest',''))]
    return result


def accept_choice(ident):
    l=link()
    if ident == l.device_id():
        endpoint='http://127.0.0.1:11434'
    elif any(p['id']==ident for p in l.load_peers()): endpoint='fleet://'+ident
    else: raise ValueError("That AI computer isn't paired here.")
    config.update(CONF,lambda d:d.setdefault('ask',{}).update(endpoints=[endpoint],providers=['local']))
    return {'ok':True}


def main(a):
    if a == ['list']:
        result={'peers':[{'id':p['id'],'name':p.get('name') or p['id']} for p in link().load_peers() if p.get('role') not in ('helper','help-target')], 'sharing':fleet_allowed(config.read(CONF)), 'id':link().device_id(), 'source':next((ep[8:] for ep in config.read(CONF).get('ask', {}).get('endpoints', []) if ep.startswith('fleet://')), 'here')}
    elif len(a)==2 and a[0]=='use':
        accept_choice(a[1])
        result={'ok':True,'message':'Ask will send questions and checks to that paired computer over the encrypted fleet link.'}
    elif a == ['provide-for-fleet']:
        config.update(CONF,lambda d:d.update(sharePrivateAi=True))
        main(['use-for-fleet',link().device_id()]); return
    elif len(a)==2 and a[0]=='use-for-fleet':
        if a[1] != link().device_id(): remote('fleet://'+a[1]+'/api/tags')  # Explicit sharing and reachability are required before changing choices.
        l=link(); failed=[]
        for peer in l.load_peers():
            result=l.ssh_to(peer,'ai-use',timeout=10,input=json.dumps({'id':a[1]})+'\n')
            if result.returncode: failed.append(peer.get('name') or peer['id'])
        accept_choice(a[1])
        result={'ok':not failed,'message':'AI choice saved on reachable computers.' + (' Could not update: '+', '.join(failed)+'. Try again when they are online.' if failed else '')}
    elif a == ['accept-choice']:
        data=json.loads(sys.stdin.readline(1024)); result=accept_choice(data['id'])
    elif a == ['here']:
        config.update(CONF,lambda d:d.setdefault('ask',{}).update(endpoints=['http://127.0.0.1:11434'],providers=['local']))
        result={'ok':True}
    elif len(a)==2 and a[0]=='share' and a[1] in ('on','off'):
        config.update(CONF,lambda d:d.update(sharePrivateAi=a[1]=='on')); result={'ok':True}
    elif len(a)==2 and a[0]=='serve': result=serve(a[1])
    else: raise ValueError(__doc__)
    print(json.dumps(result))

if __name__ == '__main__':
    from starchaser_cli import safe_streams
    safe_streams()
    if any(word in ('-h', '--help', 'help') for word in sys.argv[1:]):
        print(__doc__)
        sys.exit(0)
    try: main(sys.argv[1:])
    except (OSError,RuntimeError,ValueError) as e: print(json.dumps({'error':str(e)})); sys.exit(1)
