import os
import subprocess
import sys
from pathlib import Path

workdir = '/home/openclaw/.openclaw/workspace/kr_evening_briefing/kr_evening_briefing'
venv_python = str(Path(workdir) / '.venv' / 'bin' / 'python')
fetch_log = '/tmp/krx_valuation_fetch.log'
brief_err = '/tmp/kr_evening_briefing.err'

with open(fetch_log, 'w') as f:
    subprocess.run([venv_python, 'krx_valuation_fetch.py'], cwd=workdir, stdout=f, stderr=subprocess.STDOUT, text=True)

env = os.environ.copy()
env['KR_EVENING_SEND_DIRECT'] = '0'
with open(brief_err, 'w') as errf:
    res = subprocess.run([venv_python, 'run_kr_evening_briefing.py'], cwd=workdir, stdout=subprocess.PIPE, stderr=errf, text=True, env=env)

out = (res.stdout or '').strip()
if out:
    print(out)
    sys.exit(0)

fetch_text = ''
try:
    fetch_text = Path(fetch_log).read_text()
except Exception:
    pass

if any(x in fetch_text for x in ['GenerateOTP failed', 'LOGOUT', 'KRX_COOKIE missing']):
    print('[이브닝 마켓 브리핑 오류] KRX valuation fetch 실패')
elif Path(brief_err).exists() and Path(brief_err).stat().st_size > 0:
    print('[이브닝 마켓 브리핑 오류] run_kr_evening_briefing 실패')
else:
    print('[이브닝 마켓 브리핑 오류] 출력 없음')
