"""Generate staged English learning content for every concept."""

from __future__ import annotations

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"))

LABELS = {
"apple":("apple",["an apple"]),"banana":("banana",["a banana"]),"orange_fruit":("orange",["an orange","orange fruit"]),
"water":("water",["some water"]),"milk":("milk",["some milk"]),"juice":("juice",["some juice","fruit juice"]),
"ball":("ball",["a ball"]),"doll":("doll",["a doll"]),"car_toy":("toy car",["a toy car","car toy"]),
"cup":("cup",["a cup"]),"spoon":("spoon",["a spoon"]),"shoe":("shoe",["a shoe"]),"shirt":("shirt",["a shirt"]),"book":("book",["a book"]),
"mother":("mother",["mum","mom","mummy","primary caregiver"]),"father":("father",["dad","daddy","primary caregiver"]),
"child":("child",["a child","kid"]),"therapist":("therapist",["the therapist"]),
"eat":("eat",["eating"]),"drink":("drink",["drinking"]),"sleep":("sleep",["sleeping"]),"play":("play",["playing"]),
"give":("give",["giving"]),"wash":("wash",["washing"]),"cut":("cut",["cutting"]),"open":("open",["opening"]),"close":("close",["closing"]),
"want":("want",["I want"]),"more":("more",["some more","again"]),"help":("help",["help me"]),"finished":("finished",["all done","done"]),
"yes":("yes",["yeah"]),"no":("no",["no thank you"]),"stop":("stop",["please stop"]),"hello":("hello",["hi","good morning","good afternoon"]),"goodbye":("goodbye",["bye","see you"]),
"dog":("dog",["a dog"]),"cat":("cat",["a cat"]),"hand":("hand",["a hand"]),"foot":("foot",["a foot"]),"mouth":("mouth",["a mouth"]),"eye":("eye",["an eye"]),
"big":("big",["large","the big one"]),"small":("small",["little","the small one"]),"red":("red",["the red one"]),"green":("green",["the green one"]),"blue":("blue",["the blue one"]),
"in":("in",["inside"]),"on":("on",["on top of"]),"under":("under",["below"]),"one":("one",["just one"]),"all":("all",["all of them","every one"]),"none":("none",["not any","zero"]),
"home":("home",["at home"]),"school":("school",["at school"]),"clinic":("clinic",["the clinic","therapy clinic"]),
"happy":("happy",["glad"]),"sad":("sad",["unhappy"]),"snack_time":("snack time",["time for a snack"]),"hand_washing":("hand washing",["washing hands","wash hands"])
}

SIMPLE = {
"apple":"This is an apple. It is a fruit we can eat.","banana":"This is a banana. It has a peel.","orange_fruit":"This is an orange. It is a round citrus fruit.",
"water":"This is water. We can drink it.","milk":"This is milk. It is a drink.","juice":"This is juice. It is a drink made from fruit or vegetables.",
"ball":"This is a ball. It can roll, bounce or be thrown.","doll":"This is a doll. A doll is used for pretend play.","car_toy":"This is a toy car. It is small and used for play.",
"cup":"This is a cup. A cup holds a drink.","spoon":"This is a spoon. We can scoop or stir with it.","shoe":"This is a shoe. A shoe goes on a foot.","shirt":"This is a shirt. A shirt is worn on the upper body.","book":"This is a book. We can look at or read its pages.",
"mother":"This person is the child's mother or primary caregiver.","father":"This person is the child's father or primary caregiver.","child":"This person is a child.","therapist":"This person is a therapist helping during a therapy activity.",
"eat":"The person is eating food.","drink":"The person is drinking a liquid.","sleep":"The person is sleeping.","play":"The person is playing for enjoyment.","give":"One person is giving something to another person.","wash":"The person is washing something to make it clean.","cut":"The person is cutting something into parts.","open":"The person is opening something so it can be accessed.","close":"The person is closing something so it is shut.",
"want":"Want tells someone what a person would like.","more":"More means an additional amount or another turn.","help":"Help asks someone for assistance.","finished":"Finished means the item or activity has ended.","yes":"Yes is an affirmative answer.","no":"No is a refusal or negative answer.","stop":"Stop tells someone to end an action immediately.","hello":"Hello begins or acknowledges an interaction.","goodbye":"Goodbye marks the end of an interaction or departure.",
"dog":"This is a dog. Dogs can look different from one another.","cat":"This is a cat. Cats can look different from one another.","hand":"This is a hand at the end of an arm.","foot":"This is a foot at the end of a leg.","mouth":"This is a mouth.","eye":"This is an eye. Eye contact is not required.",
"big":"This one is big compared with the other one.","small":"This one is small compared with the other one.","red":"This object is red.","green":"This object is green.","blue":"This object is blue.",
"in":"The target is in the container.","on":"The target is on and touching the supporting surface.","under":"The target is under the reference object.","one":"There is exactly one target item.","all":"All means every item in the relevant group.","none":"None means there are no target items.",
"home":"This is a home, a place where someone lives.","school":"This is a school, a place for learning.","clinic":"This is a clinic where healthcare or therapy happens.",
"happy":"The person feels happy. Face, body and situation give clues.","sad":"The person feels sad. Tears are not required.","snack_time":"It is snack time: a small amount of food or drink between meals.","hand_washing":"Hand washing includes water, soap, rubbing, rinsing and drying."
}

COUNT_NOUNS={"apple","banana","orange_fruit","ball","doll","car_toy","cup","spoon","shoe","shirt","book","dog","cat","hand","foot","mouth","eye"}
ACTIONS={"eat","drink","sleep","play","give","wash","cut","open","close"}
PEOPLE={"mother","father","child","therapist"}
ATTRIBUTES={"big","small","red","green","blue"}
RELATIONS={"in","on","under"}
QUANTITIES={"one","all","none","more"}
PLACES={"home","school","clinic"}
EMOTIONS={"happy","sad"}
SOCIAL={"want","help","finished","yes","no","stop","hello","goodbye"}
SOCIAL_IDENTIFY={
"want":["Show me who wants something.","Find the person making a request.","Which picture shows someone communicating what they want?"],
"help":["Show me who needs help.","Find the person asking for help.","Which picture shows someone requesting assistance?"],
"finished":["Show me who is finished.","Find the activity that is finished.","Which picture shows that the activity has ended?"],
"yes":["Show me yes.","Find the person agreeing.","Which response means yes?"],
"no":["Show me no.","Find the person refusing.","Which response means no?"],
"stop":["Show me who is saying stop.","Find the request to stop.","Which picture shows someone asking for an action to end now?"],
"hello":["Show me a greeting.","Find the person saying hello.","Which picture shows the beginning of an interaction?"],
"goodbye":["Show me goodbye.","Find the person leaving.","Which picture shows the end of an interaction?"]}
SOCIAL_REQUESTS={
"want":["Want.","I want that.","I want {requested_item}, please."],"help":["Help.","Help me.","Please help me with this."],
"finished":["Finished.","All done.","I am finished with this."],"yes":["Yes.","Yes, please.","Yes, I agree."],
"no":["No.","No, thank you.","I do not want that."],"stop":["Stop.","Please stop.","I need this to stop now."],
"hello":["Hello.","Hi there.","Hello, it is good to see you."],"goodbye":["Goodbye.","Bye for now.","Goodbye, I will see you later."]}
SOCIAL_CHOICES={
"want":["Do you want this or something else?","Choose what you want."],
"help":["Do you want help or time to try by yourself?","Choose: help or try by myself."],
"finished":["Are you finished or do you want to continue?","Choose: finished or keep going."],
"yes":["Is your answer yes or no?","Choose the answer that means yes."],
"no":["Is your answer no or yes?","Choose the answer that means no."],
"stop":["Do you want to continue or stop?","Choose: keep going or stop."],
"hello":["Do you want to say hello or wait?","Choose a way to greet the person."],
"goodbye":["Do you want to stay or say goodbye?","Choose a way to end the interaction."]}

def path_for(c): return ROOT/"concepts"/Path(*c["category"].split("."))/c["key"]/"locales"/"en"
def article(label): return "an" if label[0].lower() in "aeiou" else "a"

def identify(k,label):
    if k in SOCIAL: return SOCIAL_IDENTIFY[k]
    if k in ACTIONS: return [f"Show me who is {LABELS[k][1][0]}.",f"Find {LABELS[k][1][0]}.",f"Which picture shows someone who is {LABELS[k][1][0]}?"]
    if k in ATTRIBUTES: return [f"Show me the {label} one.",f"Find something {label}.",f"Which one is {label}?"]
    if k in RELATIONS: return [f"Show me the one that is {label}.",f"Find where it is {label}.",f"Which picture shows {label}?"]
    if k in QUANTITIES: return [f"Show me {label}.",f"Find the group that means {label}.",f"Which picture shows {label}?"]
    if k in EMOTIONS: return [f"Show me who feels {label}.",f"Find the {label} person.",f"Which person looks {label}?"]
    if k in PEOPLE: return [f"Show me the {label}.",f"Find the {label}.",f"Who is the {label}?"]
    if k in PLACES: return [f"Show me {label}.",f"Find the picture of {label}.",f"Which place is {label}?"]
    return [f"Show me {article(label)} {label}.",f"Find the {label}.",f"Which one is the {label}?"]

def choices(k,label):
    if k in SOCIAL: return SOCIAL_CHOICES[k]
    if k in ACTIONS: return [f"Do you want to {label} or {{alternative_action}}?",f"Choose: {label} or {{alternative_action}}."]
    if k in ATTRIBUTES: return [f"Do you want the {label} one or the {{alternative_attribute}} one?",f"Choose the {label} one or the {{alternative_attribute}} one."]
    if k in PLACES: return [f"Are we going to {label} or {{alternative_place}}?",f"Choose a place: {label} or {{alternative_place}}."]
    if k in COUNT_NOUNS: return [f"Do you want the {label} or the {{alternative_object}}?",f"Choose: {label} or {{alternative_object}}."]
    return [f"Do you want {label} or {{alternative_choice}}?",f"Choose {label} or {{alternative_choice}}."]

def requests(k,label):
    if k in SOCIAL: return SOCIAL_REQUESTS[k]
    if k in ACTIONS: return [label.capitalize()+".",f"Want to {label}.",f"I want to {label}, please."]
    if k in COUNT_NOUNS: return [label.capitalize()+".",f"Want {article(label)} {label}.",f"I want {article(label)} {label}, please."]
    if k in PLACES: return [label.capitalize()+".",f"Go to {label}.",f"I want to go to {label}."]
    if k in ATTRIBUTES: return [label.capitalize()+".",f"Want the {label} one.",f"I want the {label} one, please."]
    if k in RELATIONS: return [label.capitalize()+".",f"Put it {label}.",f"Please put it {label} {{reference_object}}."]
    if k in EMOTIONS: return [label.capitalize()+".",f"Feel {label}.",f"I feel {label}."]
    return [label.capitalize()+".",f"Want {label}.",f"I want {label}, please."]

def questions(k,label):
    if k in SOCIAL: return [("What is the person communicating?",label.capitalize()+"."),(f"Does this mean {label}?","Yes."),("What could the communication partner do next?","Accept a safe respectful response that honors the message.")]
    if k in ACTIONS: return [("What is the person doing?",LABELS[k][1][0].capitalize()+"."),(f"Is the person {LABELS[k][1][0]}?","Yes."),("What happens next?","Accept any contextually accurate answer.")]
    if k in PEOPLE: return [("Who is this?",label.capitalize()+"."),(f"Is this the {label}?","Yes."),("What is this person doing?","Accept the visible action.")]
    if k in PLACES: return [("Where are they?",label.capitalize()+"."),(f"Is this {label}?","Yes."),("What happens here?","Accept a contextually accurate activity.")]
    if k in EMOTIONS: return [("How does the person feel?",label.capitalize()+"."),(f"Does the person feel {label}?","Yes."),("What clues show that feeling?","Accept congruent face, body or situation cues.")]
    if k in RELATIONS: return [("Where is the target?",label.capitalize()+"."),(f"Is it {label} the reference object?","Yes."),("Can you put another one in the same place?","Accept an accurate placement.")]
    if k in ATTRIBUTES: return [("What is it like?",label.capitalize()+"."),(f"Is it {label}?","Yes."),(f"Can you find another {label} one?","Accept a valid new example.")]
    if k in QUANTITIES: return [("How many or how much?",label.capitalize()+"."),(f"Does this show {label}?","Yes."),("Can you make the same amount?","Accept an equivalent set or action.")]
    return [("What is this?",label.capitalize()+"."),(f"Is this {article(label)} {label}?","Yes."),(f"What can we do with the {label}?","Accept a safe contextually accurate function.")]

FEEDBACK=[
{"semantic_key":"feedback.acknowledge","text":"You chose one.","use":"Acknowledge any valid selection without judging."},
{"semantic_key":"feedback.correct","text":"That matches.","use":"Neutral confirmation; pair with persistent visual highlighting."},
{"semantic_key":"feedback.correct_independent","text":"You found it by yourself.","use":"Optional specific acknowledgement of independence."},
{"semantic_key":"feedback.retry","text":"Let's look again.","use":"Invite review without blame or a red error cue."},
{"semantic_key":"feedback.model","text":"This one shows the answer.","use":"Use with a visual model; do not score as independent."},
{"semantic_key":"feedback.no_response","text":"We can wait, pause, or try another way.","use":"Do not convert no response into incorrect."},
{"semantic_key":"feedback.stop","text":"We stopped.","use":"Confirm immediately when stop is communicated."}
]

def caregiver(k,label):
    return [
      f"Confirm that '{label}' is meaningful and appropriate for this learner before teaching it.",
      f"Begin with a real or highly familiar example of {label}; name it once, then allow quiet processing time.",
      "Offer two meaningful choices and accept touch, pointing, eye gaze, gesture, sign, AAC, vocalization or speech.",
      "Wait at least five seconds before adding a prompt unless safety requires immediate help.",
      "Record what the learner did before prompting; prompted success is useful but is not independent mastery.",
      f"Practice {label} with at least three varied examples, two people and two everyday settings when appropriate.",
      "Do not test repeatedly after distress, fatigue, refusal or a stop signal; pause and honor communication.",
      "Model the learner's approved AAC form while speaking naturally; never remove AAC to encourage speech.",
      "Use the family's preferred words and routines, and ask before correcting a culturally or regionally valid alternative.",
    ]

updated=0
for c in PLAN["concepts"]:
    k=c["key"]; label,alternates=LABELS[k]
    content={
      "schema_version":1,"concept_key":k,"language":"en","locale":"en","status":"draft_needs_english_slp_review",
      "labels":{"preferred":label,"display":label.capitalize(),"aac_short":label.capitalize(),"natural_alternates":alternates,"usage_note":"Select family-preferred and context-appropriate wording; alternatives are not automatically interchangeable in every sentence."},
      "identification_prompts":[{"semantic_key":f"{k}.identify.{i+1}","text":x,"difficulty":i+1,"answer_position_cue":"prohibited"} for i,x in enumerate(identify(k,label))],
      "choice_prompts":[{"semantic_key":f"{k}.choice.{i+1}","text":x,"difficulty":i+1,"slots":[s for s in ["alternative_object","alternative_action","alternative_attribute","alternative_place","alternative_choice"] if "{"+s+"}" in x]} for i,x in enumerate(choices(k,label))],
      "functional_requests":[{"semantic_key":f"{k}.request.{i+1}","text":x,"difficulty":i+1,"accept_as_functional":True} for i,x in enumerate(requests(k,label))],
      "descriptions":[{"semantic_key":f"{k}.describe.simple","text":SIMPLE[k],"difficulty":1},{"semantic_key":f"{k}.describe.expanded","text":SIMPLE[k]+" Look at the target and the surrounding clues.","difficulty":2}],
      "questions":[{"semantic_key":f"{k}.question.{i+1}","prompt":q,"expected_answer":a,"difficulty":i+1,"accept_equivalent_meaning":True} for i,(q,a) in enumerate(questions(k,label))],
      "feedback":FEEDBACK,
      "caregiver_and_clinician_directions":[{"step":i+1,"text":x} for i,x in enumerate(caregiver(k,label))],
      "delivery":{"tone":"warm neutral age-respectful","default_wait_seconds":5,"speech_required":False,"audio_required":False,"avoid":["baby talk unless preferred by learner","rapid repeated testing","position or colour hints","forced eye contact","withholding AAC","compliance language","praise that evaluates the person rather than the response"]},
      "review":{"required":["English-language review","speech-language-professional review","AAC review","accessibility review","family vocabulary review"],"approved":False}
    }
    p=path_for(c)/"learning-content.json"; text=json.dumps(content,ensure_ascii=False,indent=2)+"\n"
    if not p.exists() or p.read_text(encoding="utf-8")!=text: p.write_text(text,encoding="utf-8"); updated+=1
print(f"English learning content ready: {len(PLAN['concepts'])} concepts; {updated} files updated")
