"""Build a tiny synthetic dataset: messy meeting requests -> strict JSON.

Writes data/train.jsonl, data/valid.jsonl, data/test.jsonl in the
chat "messages" format that mlx_lm.lora reads directly.
"""
import json
import random
from pathlib import Path

SYSTEM = (
    "Extract the meeting from the message. Reply with JSON only: "
    '{"title": str, "day": str, "time": "HH:MM", "duration_min": int, "people": [str]}'
)

TITLES = ["design sync", "1:1", "roadmap review", "standup", "budget check-in",
          "hiring debrief", "launch retro", "coffee chat", "sprint planning",
          "customer call", "offsite prep", "interview loop", "demo run-through",
          "pricing review", "onboarding walkthrough"]
PEOPLE = ["Priya", "Tom", "Aiko", "Marcus", "Lena", "Diego", "Sam", "Wei",
          "Fatima", "Jonas", "Ravi", "Chloe", "Omar", "Hana", "Leo", "Nia"]
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
DAY_SAY = {d: [d, d.lower(), d[:3], d[:3].lower(), "next " + d.lower()] for d in DAYS}


def say_time(h, m):
    """Many ways a human writes a time. The label is always 24h HH:MM."""
    h12 = h % 12 or 12
    ampm = "am" if h < 12 else "pm"
    opts = [f"{h12}{ampm}" if m == 0 else f"{h12}:{m:02d}{ampm}",
            f"{h12}:{m:02d} {ampm.upper()}",
            f"{h:02d}:{m:02d}"]
    if m == 30:
        opts.append(f"half past {h12}")
    if m == 15:
        opts.append(f"quarter past {h12}")
    if m == 45:
        opts.append(f"quarter to {(h + 1) % 12 or 12}")
    if h == 12 and m == 0:
        opts.append("noon")
    return random.choice(opts)


def say_duration(mins):
    if mins is None:
        return ""
    opts = {15: ["15 min", "a quick 15"], 30: ["30 mins", "half an hour"],
            45: ["45 minutes", "45m"], 60: ["an hour", "1h", "60 min"],
            90: ["90 minutes", "an hour and a half"],
            120: ["2 hours", "two hours", "120 min"]}[mins]
    return random.choice(opts)


def say_people(ppl):
    if len(ppl) == 1:
        return ppl[0]
    return ", ".join(ppl[:-1]) + random.choice([" and ", " & "]) + ppl[-1]


TEMPLATES = [
    "can we do the {title} with {people} on {day} at {time}{dur_sfx}?",
    "{people} + me, {title}, {day} {time}{dur_sfx}",
    "hey! booking {title} for {day} @ {time}{dur_sfx}. inviting {people}",
    "Reminder: {title} {day} {time}{dur_sfx} w/ {people}. pls confirm",
    "move the {title} to {day}, {time}{dur_sfx}. {people} can make it",
    "{day} {time} works for the {title}{dur_sfx}? adding {people}",
    "ok so {people} want a {title}. thinking {day} around {time}{dur_sfx}",
    "{Title}. {Day}. {time}. Me, {people}.{dur_sfx_sent}",
    "Could you set up a {title} for {day} at {time}? Bring in {people}.{dur_sfx_sent}",
    "Rescheduling our {title} to {day} {time}. Attendees: {people}.{dur_sfx_sent}",
    "{title} {day} {time} ({dur_paren}) - {people}",
    "Can {people} and I do a {title} {day} at {time}{dur_sfx}?",
]


def example():
    title = random.choice(TITLES)
    ppl = random.sample(PEOPLE, random.randint(1, 3))
    day = random.choice(DAYS)
    h, m = random.choice(range(8, 18)), random.choice([0, 0, 15, 30, 45])
    mins = random.choice([15, 30, 45, 60, 90, 120, None])
    dur = say_duration(mins)
    say_day = random.choice(DAY_SAY[day])
    text = random.choice(TEMPLATES).format(
        title=title, Title=title.capitalize(), people=say_people(ppl),
        day=say_day, Day=say_day.capitalize(), time=say_time(h, m),
        dur_sfx=f", {dur}" if dur else "",
        dur_sfx_sent=f" {dur.capitalize()}." if dur else "",
        dur_paren=dur or "30 min")
    label = {"title": title, "day": day, "time": f"{h:02d}:{m:02d}",
             "duration_min": mins or 30,  # house rule: no duration -> 30
             "people": ppl}
    return {"messages": [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": text},
        {"role": "assistant", "content": json.dumps(label)},
    ]}


def main():
    random.seed(0)
    out = Path("data")
    out.mkdir(exist_ok=True)
    for name, n in [("train", 600), ("valid", 60), ("test", 100)]:
        with open(out / f"{name}.jsonl", "w") as f:
            for _ in range(n):
                f.write(json.dumps(example()) + "\n")
        print(f"wrote {n:>3} rows -> data/{name}.jsonl")


if __name__ == "__main__":
    main()
