#!/usr/bin/env python3
# summary: Set up and manage private AI on this computer.
"""Private AI setup and local model manager. status, start, pause, models, update MODEL, remove MODEL yes, speed MODEL. No terminal window."""
import fcntl
import json
import os
import re
import runpy
import shutil
import signal
import subprocess
import sys
import time
import urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_ai_config as config
import starchaser_ai_quality as quality

ROOT = Path(os.environ.get('XDG_STATE_HOME', Path.home() / '.local/state')) / 'starchaser/private-ai'
ENDPOINT = 'http://127.0.0.1:11434'
STATE = ROOT / 'progress.json'
SETUP_HELPER = '/usr/local/lib/starchaser/starchaser-admin-private-ai'


def valid_model(name):
    return isinstance(name, str) and bool(re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.:-]{0,100}', name)) and '..' not in name


def save(**state):
    ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    state['updated'] = time.time()
    config.write(STATE, state)


def status():
    try: return json.loads(STATE.read_text())
    except (OSError, ValueError): return {'phase':'idle','message':'Private AI is optional. Built-in help always works.'}


def api(path, body=None, method=None, timeout=15):
    req = urllib.request.Request(ENDPOINT + path, data=json.dumps(body).encode() if body is not None else None, headers={'Content-Type':'application/json'}, method=method)
    return urllib.request.urlopen(req, timeout=timeout)


def stream(path, body):
    with api(path, body, timeout=120) as response:
        for line in response:
            if line.strip():
                packet = json.loads(line)
                if packet.get('error'): raise RuntimeError(packet['error'])
                yield packet


def pull(model, with_voice=False):
    total = completed = 0
    layers = {}
    for packet in stream('/api/pull', {'name':model,'stream':True}):
        if packet.get('total'):
            ident=packet.get('digest','model')
            previous=layers.get(ident,(0,0))
            layers[ident]=(packet['total'],packet.get('completed',previous[1]))
        total=sum(t for t,c in layers.values())
        completed=sum(c for t,c in layers.values())
        save(phase='downloading', model=model, withVoice=with_voice, total=total, completed=completed, message='Downloading private AI. You can pause and resume.')
    return total


def recommend_for_hardware(ram, graphics):
    choices=[(15,10,'gemma4:12b','7.7 GB'),(9.5,6,'gemma4:e2b','4.6 GB'),(0,0,'qwen3:1.7b','1.4 GB')]
    _,_,model,size=next(row for row in choices if ram>=row[0] and (not graphics or graphics>=row[1]))
    return {'model':model,'download':size,'bytes':round(float(size.split()[0])*1e9),
            'reason':f'Recommended for {ram:.0f} GB of memory' + (f' and {graphics:g} GB of graphics memory.' if graphics else '. This computer will use its available graphics hardware or processor.')}


def recommendation():
    engine=runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-ask')))
    graphics=0
    try:
        result=subprocess.run(['nvidia-smi','--query-gpu=memory.total','--format=csv,noheader,nounits'],capture_output=True,text=True,timeout=3)
        graphics=max(float(line)/1024 for line in result.stdout.splitlines())
    except (OSError,ValueError,subprocess.SubprocessError):
        for memory in Path('/sys/class/drm').glob('card*/device/mem_info_vram_total'):
            try: graphics=max(graphics,int(memory.read_text())/1024**3)
            except (OSError,ValueError): pass
    return recommend_for_hardware(engine['mem_gb'](),graphics)


def setup_failure(code, detail=''):
    """What to do next, by how the root helper ended (pkexec: 126 not approved, 127 could not run it)."""
    if code == 127 and ('No such file' in detail or not os.access(SETUP_HELPER, os.X_OK)):
        return 'Part of private AI setup is missing from this computer. Install updates in Settings > Updates, then choose Resume.'
    if code in (126, 127):
        return 'The password prompt was closed or not approved. Choose Resume and approve it to continue.'
    if code == 3:
        return "Private AI was installed but didn't start. Restart the computer, then choose Resume."
    return "Private AI couldn't be installed. Check the internet connection and install updates in Settings > Updates, then choose Resume."


def worker(model, with_voice=False):
    ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    with open(ROOT / 'lock', 'w') as lock:
        try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError: return
        (ROOT / 'pid').write_text(f'{os.getpid()} {Path(f"/proc/{os.getpid()}/stat").read_text().rsplit(")",1)[1].split()[19]}')
        def paused(*_):
            old = status(); old.pop('updated', None)
            save(**{**old, 'phase':'paused','model':model,'message':'Paused. Resume continues the download.'})
            raise SystemExit(0)
        signal.signal(signal.SIGTERM, paused)
        try:
            voice = runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-ask-voice')))
            need_voice = with_voice and not voice['voice_ready']()
            try:
                with api('/api/tags'): pass
                need_ai = False
            except OSError:
                need_ai = True
            if need_ai or (need_voice and not shutil.which('whisper-cli')):
                save(phase='installing', model=model, withVoice=with_voice, message='Setting up private AI' + (' and voice' if with_voice else '') + '. Approve the password prompt to install and start it.')
                result = subprocess.run(['pkexec',SETUP_HELPER,'ai-voice' if with_voice else 'ai'], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
                if result.returncode:
                    config.write(ROOT / 'setup-error.json', {'code':result.returncode,'detail':result.stderr[-2000:]})
                    raise RuntimeError(setup_failure(result.returncode, result.stderr))
                for _ in range(60):
                    try:
                        with api('/api/tags'): break
                    except OSError: time.sleep(1)
                else: raise RuntimeError("Private AI didn't start. Resume to try again.")
            voice_failed = need_voice and voice['setup_voice'](install=False) is False
            quality.record(model, '', 'testing')
            total = pull(model, with_voice)
            with api('/api/tags') as response:
                tag = next((m for m in json.load(response).get('models', []) if m.get('name') == model), {})
            def progress(passed):
                save(phase='testing', model=model, withVoice=with_voice, message=f'Checking private AI: {passed + 1} of 5. Built-in help is available while you wait.')
            if not quality.verify(model, tag.get('digest', ''), api, progress):
                next_model = 'qwen3:4b' if model == 'qwen3:1.7b' else ''
                save(phase='quality-failed', model=model, withVoice=with_voice, voiceFailed=voice_failed, nextModel=next_model,
                     message="Private AI didn't pass its checks. Ask will use built-in help." + (" You can try a larger model." if next_model else ""))
                return
            config.update(Path.home() / '.config/starchaser/ai.json', lambda d: d.setdefault('ask', {}).update(providers=['local'], endpoints=[ENDPOINT]))
            # Keep the voice result, not a standing request to reinstall it on model updates.
            save(phase='ready', model=model, voiceFailed=voice_failed, total=total, completed=total, message='Ready. Your questions can stay on this computer.')
            from starchaser_ask_session import start as graphical_start
            graphical_start([sys.executable, str(Path(__file__).resolve()), 'ready-notice'])
        except Exception as error:
            save(phase='error', model=model, withVoice=with_voice, message=str(error)[:300])
        finally:
            (ROOT / 'pid').unlink(missing_ok=True)


def start(model=None, with_voice=None):
    model = model or status().get('model') or recommendation()['model']
    if with_voice is None: with_voice = status().get('withVoice', False)
    if not valid_model(model): raise ValueError('Choose a valid model name.')
    ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    from starchaser_ask_session import start as graphical_start
    graphical_start([sys.executable, str(Path(__file__).resolve()), 'worker', model] + (['--voice'] if with_voice else []))
    return {'ok':True}


def pause():
    # Match process identity as well as pid; never signal a process that reused a stale pid.
    try:
        pid, stamp = (ROOT / 'pid').read_text().split()
        if Path(f'/proc/{int(pid)}/stat').read_text().rsplit(')',1)[1].split()[19] == stamp:
            os.kill(int(pid), signal.SIGTERM)
    except (OSError, ValueError): pass
    return {'ok':True}


def speed_message(count, seconds):
    if not seconds: return 'Speed was not reported.'
    rate = count / seconds
    band = 'slow' if rate < 10 else 'fine' if rate <= 30 else 'fast'
    return f'About {rate:.0f} words a second ({band})'


def ready_notice():
    notice = ['starchaser', 'notify', '-a', 'Ask', '-i', str(Path(__file__).resolve().parents[1] / 'share/branding/svg/starchaser-ask.svg'), '-w', '-A', 'ask=Ask a question', 'Private AI is ready', 'Ask can now answer on this computer.']
    token = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}') / 'starchaser-notifications' / 'token'
    try:
        with token.open() as credential:
            notice.insert(2, f'--credential-fd={credential.fileno()}')
            reply = subprocess.run(notice, capture_output=True, text=True, pass_fds=(credential.fileno(),), check=False)
        if reply.stdout.strip() == 'ask': subprocess.Popen(['starchaser', 'ask', 'ui'], start_new_session=True)
    except OSError:
        pass  # Setup succeeds even when the notification service has ended.


def main(a):
    if a == ['status']: result = {**status(), 'recommendation':recommendation()}
    elif a == ['ready-notice']: ready_notice(); return
    elif a == ['off']:
        config.update(Path.home() / '.config/starchaser/ai.json', lambda d: d.setdefault('ask', {}).update(providers=[p for p in d.get('ask', {}).get('providers', ['local']) if p != 'local']))
        save(phase='off', model=status().get('model'), message='Private AI is off. Downloaded models are kept.')
        result = {'ok':True}
    elif a in (['start'], ['start', '--voice']): result = start(with_voice='--voice' in a)
    elif a == ['upgrade'] and status().get('nextModel'): result = start(status()['nextModel'])
    elif a == ['pause']: result = pause()
    elif a == ['models']:
        with api('/api/tags') as response: result = json.load(response)
        result['recommendation'] = recommendation()
        # Hardware text stays local and helps identify why a smaller model may be faster.
        result['graphics'] = runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-ask')))['gpu']()
    elif len(a) in (2, 3) and a[0] == 'worker' and valid_model(a[1]) and (len(a) == 2 or a[2] == '--voice'): worker(a[1], '--voice' in a); return
    elif len(a) == 2 and a[0] == 'update' and valid_model(a[1]): result = start(a[1])
    elif len(a) == 3 and a[0] == 'remove' and a[2] == 'yes' and valid_model(a[1]):
        with api('/api/delete', {'model':a[1]}, method='DELETE') as response: response.read()
        if status().get('model') == a[1]: save(phase='idle',message='Model removed. Turn on private AI to download the recommendation again.')
        result = {'ok':True}
    elif len(a) == 2 and a[0] == 'speed' and valid_model(a[1]):
        with api('/api/generate', {'model':a[1], 'prompt':'Count from one to ten.', 'stream':False,'options':{'num_predict':32}}, timeout=120) as response: data=json.load(response)
        seconds = data.get('eval_duration',0) / 1e9
        result = {'message':speed_message(data.get('eval_count',0), seconds)}
    else: sys.exit(__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, ValueError, RuntimeError) as e:
        print(json.dumps({'ok':False,'phase':'error','message':str(e)[:300]})); sys.exit(1)
