#!/usr/bin/env python3
from pathlib import Path
import json
import re

root = Path(__file__).resolve().parents[1]
script = root / "script/script_self_voice.txt"
text = script.read_text(encoding="utf-8")
low = text.lower()

groups = {
    "air_conduction": ["air conduction", "dẫn truyền qua không khí"],
    "bone_conduction": ["bone conduction", "dẫn truyền qua xương"],
    "voice_production": ["dây thanh", "nếp gấp thanh âm", "vocal folds"],
    "resonance": ["cộng hưởng", "resonance"],
    "pitch_timbre_distinction": ["âm sắc", "timbre"],
    "auditory_feedback": ["auditory feedback", "phản hồi thính giác"],
    "familiarity": ["quen thuộc", "self-voice", "giọng của chính mình"],
    "recording_chain": ["microphone", "codec", "compression", "nén âm thanh"],
    "not_bad": ["không đồng nghĩa", "không có nghĩa"],
    "safety": ["đánh giá chuyên môn", "chuyên gia phù hợp đánh giá", "bác sĩ tai mũi họng"],
}
practical = {
    "headphones": ["tai nghe"],
    "mic_distance": ["khoảng cách mic", "khoảng cách microphone"],
    "room": ["phòng vang", "độ vang", "âm học phòng", "quá vang", "tiếng phòng"],
    "multiple_recordings": ["nhiều bản ghi", "nhiều lần thu", "so sánh nhiều"],
    "clarity": ["độ rõ", "rõ lời"],
}
sources = [name for name in ["Georg von Békésy", "Pascal Belin", "John Houde", "Sophie Scott"] if name.lower() in low]
forbidden = {
    word: bool(re.search(r"(?<![\wÀ-ỹ])" + re.escape(word) + r"(?![\wÀ-ỹ])", low))
    for word in ["tôi", "chúng ta", "chúng tôi"]
}
report = {
    "groups": {key: any(term.lower() in low for term in terms) for key, terms in groups.items()},
    "practical": {key: any(term.lower() in low for term in terms) for key, terms in practical.items()},
    "sources_present": sources,
    "source_count": len(sources),
    "forbidden_narrator_pronouns": forbidden,
    "self_diagnosis_boundary": any(term in low for term in ["không tự chẩn đoán", "không đủ để tự chẩn đoán", "đừng tự chẩn đoán"]),
    "bone_conduction_not_absolute": any(term in low for term in ["không phải lúc nào", "không đơn giản", "không đồng nghĩa rằng mọi giọng"]),
}
report["status"] = "PASS" if (
    all(report["groups"].values())
    and all(report["practical"].values())
    and report["source_count"] >= 3
    and not any(forbidden.values())
    and report["self_diagnosis_boundary"]
    and report["bone_conduction_not_absolute"]
) else "FAIL"
(root / "logs/script_semantic_validation.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, ensure_ascii=False))
raise SystemExit(report["status"] != "PASS")
