#!/usr/bin/env python3
# summary: Use local speech input and read Ask answers aloud.
"""Local voice for Ask: start, finish (JSON transcript), read (text on stdin). Nothing goes to a speech company."""
import json
import re
import os
import signal
import shutil
import urllib.request
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/run/user/{os.getuid()}') / 'starchaser-ask-voice'
MODEL = Path.home() / '.local/share/starchaser/speech/ggml-base.en.bin'


def transcribe(path):
    result=subprocess.run(['whisper-cli','-m',str(MODEL),'-f',str(path),'-nt','-np'],capture_output=True,text=True,timeout=90,check=True)
    text = result.stdout.strip()
    silence = text.casefold().strip('.! ') in ('you', 'thank you', '[blank_audio]') or len(re.sub(r'[^a-z]', '', text, flags=re.I)) < 2
    return {'transcript':text,'message':'Check the words, then press Enter.'} if not silence else {'error':'No speech was heard. Try again, speaking while the microphone is on.'}


def voice_ready():
    return MODEL.is_file() and bool(shutil.which('whisper-cli'))


def setup_voice(install=True):
    ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    import fcntl
    lock=open(ROOT / 'setup.lock','w')
    try: fcntl.flock(lock,fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError: return
    def progress(message, ready=False):
        (ROOT / 'setup.json').write_text(json.dumps({'message':message,'ready':ready}))
    try:
        if not shutil.which('whisper-cli'):
            if not install: raise RuntimeError("Voice software wasn't installed. Try voice setup again.")
            subprocess.run(['pkexec','/usr/local/lib/starchaser/starchaser-admin-private-ai','voice'],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        MODEL.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
        progress('Downloading the local speech model (148 MB) from Hugging Face. Audio stays here.')
        # Fixed upstream model; this is a download the person chose, never a speech request.
        req=urllib.request.Request('https://huggingface.co/ggerganov/whisper.cpp/resolve/main/ggml-base.en.bin')
        tmp=MODEL.with_suffix('.part')
        with urllib.request.urlopen(req,timeout=60) as source, tmp.open('wb') as dest:
            done=0; total=int(source.headers.get('Content-Length',0))
            while chunk:=source.read(1024*1024):
                dest.write(chunk); done+=len(chunk)
                progress(f'Downloading local speech: {done // 1000000} MB' + (f' of {total // 1000000} MB' if total else ''))
        if tmp.stat().st_size<100000000: raise RuntimeError('The speech download was incomplete. Try again.')
        os.replace(tmp,MODEL); progress('Voice is ready. Press the microphone in Ask.',True)
    except Exception:
        progress('Local voice setup could not finish. Check your connection, then try again.')
        return False
    return True


def main(a):
    ROOT.mkdir(parents=True, exist_ok=True, mode=0o700)
    if a == ['status']:
        try: result=json.loads((ROOT / 'setup.json').read_text())
        except (OSError,ValueError): result={'message':'Voice uses a local speech model (148 MB). Audio stays on this computer.'}
        result['ready']=voice_ready()
        print(json.dumps(result)); return
    if a == ['setup']:
        from starchaser_ask_session import start as graphical_start
        graphical_start([sys.executable,str(Path(__file__).resolve()),'setup-worker'])
        print(json.dumps({'message':'Setting up local voice. Approve the password prompt if speech software is missing.'})); return
    if a == ['setup-worker']:
        setup_voice(); return
    if a == ['remove']:
        if (ROOT / 'pid').exists(): raise RuntimeError('Finish the voice question before removing voice.')
        MODEL.unlink(missing_ok=True)
        (ROOT / 'setup.json').unlink(missing_ok=True)
        print(json.dumps({'ready':False,'message':'Voice was removed. You can turn it on again any time.'})); return
    if a == ['read']:
        subprocess.run(['spd-say','--wait','--pipe-mode'], input=sys.stdin.read(20000), text=True, check=True)
        return
    if len(a)==2 and a[0]=='transcribe':
        print(json.dumps(transcribe(Path(a[1])))); return
    if a == ['start']:
        if not MODEL.is_file():
            print(json.dumps({'error':"Voice isn't set up yet. Press Turn on voice."})); return
        if (ROOT / 'pid').exists(): raise RuntimeError('A voice recording is already in progress.')
        child = subprocess.Popen(['pw-record','--rate','16000','--channels','1',str(ROOT / 'question.wav')], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
        stamp = Path(f'/proc/{child.pid}/stat').read_text().rsplit(')',1)[1].split()[19]
        (ROOT / 'pid').write_text(f'{child.pid} {stamp}')
        print(json.dumps({'recording':True})); return
    if a == ['finish']:
        try:
            pid,stamp=(ROOT / 'pid').read_text().split()
            if Path(f'/proc/{int(pid)}/stat').read_text().rsplit(')',1)[1].split()[19] != stamp: raise RuntimeError('The recording ended. Try again.')
            os.kill(int(pid),signal.SIGINT)
            for _ in range(30):
                if not Path(f'/proc/{pid}').exists(): break
                time.sleep(.05)
            print(json.dumps(transcribe(ROOT / 'question.wav')))
        finally:
            (ROOT / 'pid').unlink(missing_ok=True)
            (ROOT / 'question.wav').unlink(missing_ok=True)
        return
    raise ValueError(__doc__)

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,subprocess.SubprocessError) as e:
        print(json.dumps({'error':str(e)[:300]})); sys.exit(1)
