from pathlib import Path
import hashlib
import json
import os
import subprocess
import urllib.parse
import urllib.request

ROOT = Path(__file__).resolve().parents[1]
receipt = json.loads((ROOT / "log/tts-pronunciation.json").read_text())
intro = receipt["intro"]
text = intro["tts_text"]
assert hashlib.sha256(text.encode()).hexdigest() == intro["tts_text_sha256"]
validator = subprocess.run([
    "python3",
    "/home/hermes/.hermes/skills/audio-production/gac-mai-audio/scripts/validate_tts_text_contract.py",
    "--project-root",
    str(ROOT),
], check=True, capture_output=True, text=True)
with urllib.request.urlopen("http://192.168.40.33:7862/health", timeout=20) as response:
    assert json.load(response)["status"] == "ok"
with urllib.request.urlopen("http://192.168.40.33:7862/voices", timeout=20) as response:
    voices = json.load(response)
assert "ngoc-huyen-vbee" in json.dumps(voices, ensure_ascii=False)
payload = urllib.parse.urlencode({"text": text, "voice": "ngoc-huyen-vbee"}).encode()
part = ROOT / "audio/intro-voice.wav.part"
with urllib.request.urlopen(urllib.request.Request("http://192.168.40.33:7862/tts", data=payload, method="POST"), timeout=300) as response:
    part.write_bytes(response.read())
assert part.read_bytes()[:4] == b"RIFF" and part.read_bytes()[8:12] == b"WAVE"
output = ROOT / "audio/intro-voice.wav"
os.replace(part, output)
probe = json.loads(subprocess.check_output(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(output)], text=True))
hash_value = hashlib.sha256(output.read_bytes()).hexdigest()
result = {
    "status": "completed",
    "verified": True,
    "provider": "piper-wrapper",
    "endpoint": "/tts",
    "voice": "ngoc-huyen-vbee",
    "intro_tts_text_sha256": intro["tts_text_sha256"],
    "pronunciation_receipt_sha256": hashlib.sha256((ROOT / "log/tts-pronunciation.json").read_bytes()).hexdigest(),
    "artifact_sha256": hash_value,
    "artifact_bytes": output.stat().st_size,
    "probe": probe,
}
target = ROOT / "log/intro-tts.json"
temporary = Path(str(target) + ".tmp")
temporary.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
os.replace(temporary, target)
print(json.dumps(result, ensure_ascii=False))
