#!/usr/bin/env python3
"""Explicit provider smoke with public phrases; never stores audio or credentials."""
import asyncio
import json
import os
from pathlib import Path
import shlex
import sys
import time

REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / 'server'))
from device_gateway.speech import CloudflareMeloTTS, HaihubSummary, language_for
from device_gateway.voice import configured_stt, wav_pcm


def load_provider_env():
    allowed = {'GATEWAY_CF_ACCOUNT_ID', 'GATEWAY_CF_API_TOKEN', 'GATEWAY_STT_PROVIDER', 'GATEWAY_STT_MODEL'}
    for line in (Path.home()/'.config/esp32-device-gateway/gateway.env').read_text().splitlines():
        name, sep, raw = line.partition('=')
        if sep and name in allowed:
            values = shlex.split(raw)
            if len(values) == 1:
                os.environ[name] = values[0]
    os.environ.pop('GATEWAY_STT_INITIAL_PROMPT', None)


async def main():
    load_provider_env()
    tts = CloudflareMeloTTS(os.environ['GATEWAY_CF_ACCOUNT_ID'], os.environ['GATEWAY_CF_API_TOKEN'])
    stt, summarizer = configured_stt(), HaihubSummary()
    results = {'tts': {}, 'summary': {}, 'stt': {}}
    phrases = {'chinese':'任务已经完成，所有测试都已通过。',
        'english':'The task is complete. All tests passed.',
        'mixed':'Codex 已经完成任务，pytest 全部通过。'}
    for case, text in phrases.items():
        start = time.monotonic()
        pcm = await tts.synthesize(text, language_for(text))
        duration = len(pcm)/88200
        assert 0.3 < duration < 30 and len(pcm)%2 == 0
        results['tts'][case] = dict(status='PASS', text=text, pcm_bytes=len(pcm), duration=round(duration,3),
            request_seconds=round(time.monotonic()-start,3), pcm='44100 Hz s16le mono')
        transcript = await stt.transcribe(wav_pcm(pcm))
        results['stt'][case] = dict(transcript=transcript, seconds=round(stt.last_request_seconds,3))
        print(json.dumps({case:results['tts'][case], 'stt':results['stt'][case]},ensure_ascii=False),flush=True)
    for case, state, text in [
        ('success','DONE','已修复 Gateway 问题。37 个测试全部通过。代码已经提交。'),
        ('failed','FAILED','缺少必要依赖，无法完成任务。没有提交任何修改。需要先安装依赖。'),
        ('partial','DONE','已修复 Gateway 配置并通过 37 个测试。但依赖不可用，集成测试未运行，代码尚未提交。下一步需要恢复依赖并运行集成测试。')]:
        result = await summarizer.summarize('codex','Public summary smoke',state,text)
        assert not result.get('fallback'), 'Summary provider returned fallback'
        assert result['status'] == case if case != 'failed' else result['status'] in ('failed','needs_action')
        results['summary'][case] = result
        print(json.dumps({case:result},ensure_ascii=False),flush=True)
    output=Path(sys.argv[1] if len(sys.argv)>1 else '/tmp/spoken-provider-results.json')
    output.write_text(json.dumps(results,indent=2,ensure_ascii=False)+'\n')
    print('Provider smokes PASS; report:',output,flush=True)

if __name__ == '__main__':
    try: asyncio.run(main())
    except Exception as exc:
        print('Provider smoke FAILED:',type(exc).__name__,flush=True)
        raise SystemExit(1) from None
