"""Create translation-ready semantic handoff packages for all concepts/locales."""

from __future__ import annotations

import csv
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1] / "content" / "speech"
PLAN = json.loads((ROOT / "plan" / "content-plan.json").read_text(encoding="utf-8"))

LANGUAGE_GUIDANCE = {
"en":{"locale_variants":["en-IN","en-GB","en-US"],"grammar":["Choose articles and count/mass forms from context.","Use natural child-directed imperatives without position cues.","Record regional caregiver terms as approved alternatives."],"font":"Unicode Latin font with full punctuation support"},
"hi":{"locale_variants":["hi-IN"],"grammar":["Use natural Hindi word order and postpositions; do not preserve English order mechanically.","Record grammatical gender and number agreement for nouns, adjectives and verbs.","Provide respectful and familiar pronoun/imperative variants where context changes register.","Keep Devanagari primary; transliteration is optional metadata, never the authoritative display."],"font":"Unicode Devanagari font with correct matra and conjunct shaping"},
"ta":{"locale_variants":["ta-IN","ta-LK"],"grammar":["Use natural Tamil SOV order, case suffixes and postpositions.","Record spoken child-directed forms separately from formal written forms when materially different.","Check honorific, person, number and gender agreement in verbs and caregiver language.","Keep Tamil script primary; optional transliteration must not replace native-script review."],"font":"Unicode Tamil font with correct vowel-sign shaping"},
"te":{"locale_variants":["te-IN"],"grammar":["Use natural Telugu SOV order, case markers and postpositions.","Check person, number, gender and honorific agreement in verbs.","Prefer familiar child-directed vocabulary and record meaningful regional alternatives.","Keep Telugu script primary; transliteration is optional metadata."],"font":"Unicode Telugu font with correct conjunct and vowel-sign shaping"},
"kn":{"locale_variants":["kn-IN"],"grammar":["Use natural Kannada SOV order, case suffixes and postpositions.","Check person, number, gender, tense and honorific agreement.","Separate familiar spoken forms from formal or literary forms when needed.","Keep Kannada script primary; transliteration is optional metadata."],"font":"Unicode Kannada font with correct conjunct and vowel-sign shaping"},
"ml":{"locale_variants":["ml-IN"],"grammar":["Use natural Malayalam SOV order, case suffixes and postpositions.","Check politeness, person and number choices in instructions and caregiver speech.","Record common spoken alternatives when formal written wording would sound unnatural to a child.","Keep Malayalam script primary; transliteration is optional metadata."],"font":"Unicode Malayalam font with correct chillu and conjunct shaping"},
"mr":{"locale_variants":["mr-IN"],"grammar":["Use natural Marathi word order, case/postposition patterns and verb agreement.","Record grammatical gender and number effects on adjectives and verbs.","Choose familiar versus respectful pronouns and imperatives according to partner and context.","Keep Devanagari primary and distinguish Marathi usage from Hindi look-alikes."],"font":"Unicode Devanagari font with full Marathi characters and correct shaping"},
"bn":{"locale_variants":["bn-IN","bn-BD"],"grammar":["Use natural Bengali SOV order, case markers and postpositions.","Check person and honorific level in pronouns, imperatives and verb forms.","Record regional vocabulary differences only when semantically equivalent and appropriate.","Keep Bengali script primary; transliteration is optional metadata."],"font":"Unicode Bengali font with correct conjunct and vowel-sign shaping"},
}


def concept_path(c: dict) -> Path:
    return ROOT / "concepts" / Path(*c["category"].split(".")) / c["key"]


def blank_expression(source: dict) -> dict:
    return {
        "semantic_key": source["semantic_key"],
        "source_meaning_en": source.get("text") or source.get("prompt"),
        "difficulty": source.get("difficulty"),
        "target_text": None,
        "natural_alternatives": [],
        "literal_gloss_en_optional": None,
        "transliteration_optional": None,
        "register": "child_directed_neutral",
        "grammar_notes": [],
        "pronunciation_notes": [],
        "do_not_translate_word_for_word": True,
        "status": "translation_required",
    }


queue = [["concept_key","language","package_path","translation_status","translator","native_reviewer","slp_reviewer","script_qa","audio_ready","notes"]]
updated = 0
for concept in PLAN["concepts"]:
    base = concept_path(concept)
    semantic = json.loads((base / "semantic-definition.json").read_text(encoding="utf-8"))
    english = json.loads((base / "locales" / "en" / "learning-content.json").read_text(encoding="utf-8"))
    sources = []
    for section in ["identification_prompts","choice_prompts","functional_requests","descriptions"]:
        sources.extend(english[section])
    for item in english["questions"]:
        sources.append({"semantic_key":item["semantic_key"]+".prompt","text":item["prompt"],"difficulty":item["difficulty"]})
        sources.append({"semantic_key":item["semantic_key"]+".answer","text":item["expected_answer"],"difficulty":item["difficulty"]})
    sources.extend(english["feedback"])
    for lang in PLAN["languages"]:
        code = lang["code"]
        guidance = LANGUAGE_GUIDANCE[code]
        target = {
            "preferred_term": None,
            "aac_short_label": None,
            "natural_alternatives": [],
            "avoid_terms": [],
            "part_of_speech_or_construction": None,
            "inflection_or_agreement_notes": [],
            "pronunciation": {"phonetic_or_syllable_help": None,"recording_notes": [],"audio_asset_keys": []},
            "expressions": [blank_expression(x) for x in sources],
            "caregiver_directions": [{"source_step":x["step"],"source_meaning_en":x["text"],"target_text":None,"natural_alternatives":[],"status":"translation_required"} for x in english["caregiver_and_clinician_directions"]],
        }
        if code == "en":
            target.update({"preferred_term":english["labels"]["preferred"],"aac_short_label":english["labels"]["aac_short"],"natural_alternatives":english["labels"]["natural_alternates"]})
            source_by_key = {x["semantic_key"]:(x.get("text") or x.get("prompt")) for x in sources}
            for expr in target["expressions"]:
                expr["target_text"] = source_by_key[expr["semantic_key"]]
                expr["do_not_translate_word_for_word"] = False
                expr["status"] = "english_source_draft"
            for out, src in zip(target["caregiver_directions"], english["caregiver_and_clinician_directions"]):
                out["target_text"] = src["text"]; out["status"] = "english_source_draft"
        package = {
            "schema_version":1,
            "package_key":f"{concept['key']}.{code}",
            "concept_key":concept["key"],
            "target_language":{"code":code,"name":lang["name"],"native_name":lang["native_name"],"script":lang["script"],"direction":lang["direction"],"locale_variants":guidance["locale_variants"]},
            "translation_principle":"Translate the intended meaning and communicative function natively; never map English words mechanically.",
            "semantic_source":{"meaning":semantic["meaning"],"counts_as":semantic["counts_as"],"does_not_count_as":semantic["does_not_count_as"],"relations":semantic["relations"],"safety_and_cultural_notes":semantic["safety_and_cultural_notes"]},
            "english_reference":{"preferred_label":english["labels"]["preferred"],"natural_alternates":english["labels"]["natural_alternates"],"usage_note":english["labels"]["usage_note"],"reference_only":code!="en"},
            "language_guidance":{"grammar_and_register":guidance["grammar"],"rendering_font_requirement":guidance["font"],"direction":lang["direction"],"maximum_aac_label_graphemes":18,"text_expansion_test_percent":200,"line_breaking":"review manually at game and caption widths"},
            "required_context_checks":["isolated label","identification instruction","meaningful choice","one-word functional communication","expanded request","description","question and answer","neutral feedback","caregiver direction","AAC display"],
            "target_content":target,
            "quality_checks":["meaning preserved","natural child-directed wording","register appropriate","grammar and morphology correct","regional variety recorded","AAC label concise and recognizable","no English word order imposed","script shaping and punctuation correct","audio script matches approved text","safety and consent meanings preserved"],
            "review":{"status":"english_source_review_required" if code=="en" else "translation_required","translator":None,"native_reviewer":None,"speech_language_professional":None,"cultural_notes":[],"decisions":[],"approved_at":None},
        }
        locale_dir = base / "locales" / code
        output = locale_dir / "translation-package.json"
        text = json.dumps(package,ensure_ascii=False,indent=2)+"\n"
        # Never overwrite a populated/reviewed package during a scaffold rerun.
        # Translation packages are updated by the dedicated translation workflow.
        if not output.exists():
            output.write_text(text,encoding="utf-8"); updated += 1
        queue.append([concept["key"],code,str(output.relative_to(ROOT)).replace("\\","/"),package["review"]["status"],"","","","pending","no",""])

tracking = ROOT / "tracking" / "translation-queue.csv"
with tracking.open("w",encoding="utf-8",newline="") as stream:
    csv.writer(stream).writerows(queue)
print(f"Translation packages ready: {len(PLAN['concepts']) * len(PLAN['languages'])}; {updated} files updated")
