#!/usr/bin/env python3
"""Parse a Telegram-style SYM line and store it via health_symptom_quick_add.py.

Example:
  health_symptom_from_text.py 'SYM 2026-06-23 aphthen=0 gi=1 fatigue=2 skin=0 eyes=0 joints=0 vascular=0 notes=kurz'
"""
from __future__ import annotations

import re
import shlex
import subprocess
import sys
from datetime import date
from pathlib import Path

BASE = Path('/home/agent/.hermes/assets/Gesundheit')
QUICK = BASE / 'scripts' / 'health_symptom_quick_add.py'
FIELDS = ['aphthen', 'gi', 'fatigue', 'skin', 'eyes', 'joints', 'vascular']


def parse(text: str) -> tuple[str, dict[str, int], str]:
    parts = shlex.split(text.strip())
    if not parts or parts[0].upper() != 'SYM':
        raise SystemExit('Format muss mit SYM beginnen.')
    day = date.today().isoformat()
    rest = parts[1:]
    if rest and re.fullmatch(r'\d{4}-\d{2}-\d{2}', rest[0]):
        day = rest[0]
        rest = rest[1:]
    scores = {k: 0 for k in FIELDS}
    notes = ''
    for token in rest:
        if '=' not in token:
            notes = (notes + ' ' + token).strip()
            continue
        k, v = token.split('=', 1)
        k = k.lower().strip()
        if k == 'notes':
            notes = v
        elif k in scores:
            iv = int(v)
            if iv not in (0, 1, 2, 3):
                raise SystemExit(f'{k} muss 0..3 sein')
            scores[k] = iv
    return day, scores, notes


def main() -> int:
    if len(sys.argv) < 2:
        raise SystemExit("Usage: health_symptom_from_text.py 'SYM YYYY-MM-DD aphthen=0 gi=1 ... notes=kurz'")
    day, scores, notes = parse(' '.join(sys.argv[1:]))
    cmd = [sys.executable, str(QUICK), '--date', day, '--notes', notes, '--dashboard']
    for k, v in scores.items():
        cmd.extend([f'--{k}', str(v)])
    subprocess.run(cmd, check=True)
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
