#!/usr/bin/env python3
"""One-shot CPU ASR and local chat stage. No recording or automatic shell execution."""
import argparse
import json
from pathlib import Path
import time
import urllib.request


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("audio", type=Path)
    args = parser.parse_args()
    if not args.audio.is_file():
        parser.error("Audio file does not exist")
    if Path("transcript.txt").exists() or Path("answer.txt").exists():
        parser.error("Existing output found; move it or use a fresh working directory")
    from faster_whisper import WhisperModel
    start = time.monotonic()
    model = WhisperModel("small", device="cpu", compute_type="int8")
    loaded = time.monotonic()
    segments, _ = model.transcribe(str(args.audio), vad_filter=True)
    transcript = " ".join(segment.text.strip() for segment in segments).strip()
    transcribed = time.monotonic()
    if not transcript or len(transcript) > 8000:
        parser.error("No usable short transcript; inspect the recording")
    with Path("transcript.txt").open("x", encoding="utf-8") as handle:
        handle.write(transcript + "\n")
    request = urllib.request.Request("http://127.0.0.1:11434/api/chat", data=json.dumps({
        "model": "llama3.2:3b", "stream": False,
        "options": {"num_predict": 160, "num_ctx": 4096},
        "messages": [{"role": "system", "content": "Reply concisely in plain text suitable for reading aloud. You have no tool access."},
                     {"role": "user", "content": transcript}],
    }).encode(), headers={"Content-Type": "application/json"})
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
    with opener.open(request, timeout=180) as response:
        result = json.loads(response.read(2 * 1024 * 1024))
    answer = result.get("message", {}).get("content", "").strip()
    if not answer:
        raise ValueError("No chat answer returned; transcript.txt was retained")
    with Path("answer.txt").open("x", encoding="utf-8") as handle:
        handle.write(answer + "\n")
    print(f"ASR load: {loaded-start:.2f}s; transcription: {transcribed-loaded:.2f}s; chat: {time.monotonic()-transcribed:.2f}s")
    print("Transcript:", transcript)
    print("Answer:", answer)


if __name__ == "__main__":
    main()
