"""Pencil demo school – sample chats, announcements, notifications and read state -> chats.sql
(run after seed.sql). Times are spread over the last days before the demo 'today' (Wed 2 Dec 2026 10:40)."""
out = []
def q(v):
    if v is None: return 'NULL'
    if isinstance(v, (int, float)): return str(v)
    return "'" + str(v).replace("\\", "\\\\").replace("'", "''") + "'"
def ins(t, rows):
    cols = list(rows[0].keys())
    out.append(f"INSERT INTO `{t}` ({','.join('`'+c+'`' for c in cols)}) VALUES " + ",".join("(" + ",".join(q(r.get(c)) for c in cols) + ")" for r in rows) + ";")

STAFF = {1: 'Anushka Fernando', 2: 'Ruwan Silva', 3: 'Shalini Rajan', 4: 'Kasun Jayawardena', 5: 'Fathima Rizwan', 6: 'Tharushi Wickramasinghe', 8: 'Dinesh Kumar'}
ADMIN = 'Mrs. R. Dias'
for t in ['app_messages', 'parent_messages', 'parent_posts', 'parent_post_students', 'app_notifications', 'app_chat_reads', 'app_sessions', 'app_push_subs']:
    out.append(f'DELETE FROM `{t}`;')

# ---------------- staff <-> office chats and announcements (app_messages) ----------------
M = []
def am(thread, kind, fid, name, body, at, **k):
    M.append(dict(id=len(M) + 1, thread=thread, from_kind=kind, from_id=fid, from_name=name, audience=k.get('audience'), reply_to=k.get('reply_to'),
                  body=body, expires_on=k.get('expires'), copy_of=k.get('copy_of'), created_at=at))
    return len(M)
a1 = am('all', 'admin', 1, ADMIN, 'Good morning all. Staff meeting on Friday 4 December at 1.45 pm in the library. Please bring your Term 1 test papers.', '2026-11-30 07:05:00', expires='2026-12-04')
a2 = am('all', 'admin', 1, ADMIN, 'Reminder: Term 1 test marks must be entered in the staff app by Friday 11 December.', '2026-12-01 13:30:00', expires='2026-12-11')
for sid in [1, 3, 6]:
    am(f's{sid}', 'admin', 1, ADMIN, 'Good morning all. Staff meeting on Friday 4 December at 1.45 pm in the library. Please bring your Term 1 test papers.', '2026-11-30 07:05:00', copy_of=a1)
conv = {
    1: [('staff', 'Good afternoon Madam. May I take a half day on 9 December for a medical appointment? I have applied in the app.', '2026-12-01 15:40:00'),
        ('admin', 'Yes Anushka, that is fine. Please arrange the class work with Ruwan.', '2026-12-01 16:10:00'),
        ('staff', 'Thank you Madam. I have given him the worksheets.', '2026-12-01 16:20:00'),
        ('admin', 'Thank you 🙏', '2026-12-01 16:25:00')],
    3: [('staff', 'Good morning Madam. I will be 15 minutes late today due to traffic.', '2026-12-02 07:12:00')],
    6: [('admin', 'Tharushi, are the Final Year concert costumes ready?', '2026-12-01 11:00:00'),
        ('staff', 'Not yet Madam, the tailor promised them for tomorrow.', '2026-12-01 11:20:00'),
        ('staff', 'The Final Year concert costumes have arrived.', '2026-12-02 09:40:00')],
    4: [('staff', 'Madam, I forgot to tap out yesterday – I left with the sports team. I sent a time correction.', '2026-12-01 19:02:00')],
}
for sid, msgs in conv.items():
    for kind, body, at in msgs:
        am(f's{sid}', kind, sid if kind == 'staff' else 1, STAFF[sid] if kind == 'staff' else ADMIN, body, at)
ins('app_messages', M)
last_s = {sid: max(m['id'] for m in M if m['thread'] == f's{sid}') for sid in conv}

# ---------------- announcements to parents (parent_posts) ----------------
P = [
    dict(id=1, author_kind='admin', author_id=1, author_name='School Office', scope='school', category='notice', title='Term 1 examination fee',
         body='Dear parent, the Term 1 examination fee (Rs. 3,500) is due by 10 December. You can see it under Fees in the app.', expires_on='2026-12-10', created_at='2026-12-02 08:30:00'),
    dict(id=2, author_kind='staff', author_id=1, author_name=STAFF[1], scope='class', grp='international', grade=4, division='A', subject='English', category='homework', title='English homework',
         body='Read pages 42–45 of the reader and write five sentences about your favourite character. Due Friday.', expires_on='2026-12-04', created_at='2026-12-01 13:45:00'),
    dict(id=3, author_kind='admin', author_id=1, author_name='School Office', scope='school', category='event', title='Christmas Carol Service',
         body='All parents are warmly invited to our Christmas Carol Service on Wednesday 16 December at 5.00 pm in the school auditorium.', expires_on='2026-12-16', created_at='2026-11-28 10:00:00'),
    dict(id=4, author_kind='staff', author_id=6, author_name=STAFF[6], scope='group', grp='preschool', category='event', title='Pre School concert rehearsal',
         body='Concert rehearsal on Friday 4 December from 9.00 to 11.00 am. Please send your child in the concert costume.', expires_on='2026-12-04', created_at='2026-12-02 09:15:00'),
    dict(id=5, author_kind='staff', author_id=2, author_name=STAFF[2], scope='class', grp='international', grade=4, division='A', subject='Mathematics', category='homework', title='Maths – fractions',
         body='Complete exercise 7.3 (questions 1–10) in the activity book.', expires_on='2026-12-03', created_at='2026-12-02 10:05:00'),
]
for p in P:
    for k in ['grp', 'grade', 'division', 'student_id', 'subject']: p.setdefault(k, None)
ins('parent_posts', P)

# ---------------- parent chats (parent_messages) ----------------
PM = []
def pm(staff_id, kind, fid, name, body, at, child=None, post=None):
    PM.append(dict(id=len(PM) + 1, parent_id=1, staff_id=staff_id, student_id=child, from_kind=kind, from_id=fid, from_name=name, body=body, post_id=post, created_at=at))
    return len(PM)
PAR = 'Nimal Perera / Dilani Perera'
pm(1, 'par', 1, PAR, 'Good morning Miss. Senuli has a mild fever today, so she will stay at home. We applied for leave in the app.', '2026-11-12 06:45:00', child=1)
pm(1, 'staff', 1, STAFF[1], 'Thank you for letting me know. I hope she feels better soon. I will send the class work home with her friend.', '2026-11-12 07:30:00', child=1)
pm(1, 'staff', 1, STAFF[1], 'Senuli did very well in the English unit test – 46 out of 50! 🎉', '2026-11-20 15:10:00', child=1)
pm(1, 'par', 1, PAR, 'Thank you very much Miss 🙏', '2026-12-01 19:45:00', child=1)
t1_read = len(PM) - 1
pm(6, 'staff', 6, STAFF[6], 'Good afternoon! Kavin enjoyed the sand play today and shared nicely with his friends.', '2026-11-30 12:30:00', child=2)
pm(6, 'par', 1, PAR, 'That is lovely to hear, thank you Miss.', '2026-11-30 18:10:00', child=2)
t6_read = len(PM)
pm(6, 'staff', 6, STAFF[6], 'Kavin did very well in today\'s phonics activity. ⭐', '2026-12-02 09:50:00', child=2)
pm(0, 'admin', 1, 'School Office', 'Dear parent, the Term 1 examination fee (Rs. 3,500) is due by 10 December. You can see it under Fees in the app.', '2026-12-02 08:30:00', post=1)
pm(2, 'staff', 2, STAFF[2], 'Senuli is doing well with fractions. A little more practice with word problems will help.', '2026-11-26 14:00:00', child=1)
ins('parent_messages', PM)

# ---------------- in-app alerts ----------------
S1, S2 = '7:41 AM', '8:12 AM'
N = [
    ('par', 1, 'att', 'Senuli Perera arrived at school', f'Checked in · Wed 2 Dec', 'home/attendance', '2026-12-02 07:45:00', None),
    ('par', 1, 'att', 'Kavin Perera arrived at school', f'Checked in · Wed 2 Dec', 'home/attendance', '2026-12-02 08:12:00', None),
    ('par', 1, 'chat', STAFF[6], "Kavin did very well in today's phonics activity. ⭐", 'chat:t6', '2026-12-02 09:50:00', None),
    ('par', 1, 'chat', 'School Office', 'Dear parent, the Term 1 examination fee (Rs. 3,500) is due by 10 December.', 'chat:t0', '2026-12-02 08:30:00', None),
    ('par', 1, 'marks', 'New results: Unit test 3 · English', 'Senuli Perera – tap to see the marks and graphs.', 'home/results', '2026-11-20 15:00:00', '2026-11-20 18:00:00'),
    ('par', 1, 'leave', 'Leave approved', 'Senuli Perera · 12–13 Nov · Get well soon', 'leave', '2026-11-11 19:00:00', '2026-11-11 19:30:00'),
    ('staff', 1, 'chat', ADMIN, 'Thank you 🙏', 'chat:s1', '2026-12-01 16:25:00', '2026-12-01 16:30:00'),
    ('staff', 1, 'leave', 'Leave approved', 'Fri 6 Nov · Full day', 'leave', '2026-11-05 19:00:00', '2026-11-05 19:30:00'),
    ('staff', 1, 'time', 'Time correction approved', 'Fri 27 Nov · In 7:22 AM', 'time', '2026-11-27 12:00:00', None),
    ('staff', 1, 'pchat', PAR, 'Thank you very much Miss 🙏', 'parents', '2026-12-01 19:45:00', None),
    ('admin', 1, 'leave', 'Leave request · Fathima Rizwan', 'Fri 4 Dec · Full day · Sick', 'approvals:leave', '2026-11-30 18:00:00', None),
    ('admin', 1, 'leave', 'Leave request · Dinesh Kumar', 'Thu 3 Dec · Short leave 12:30–14:00', 'approvals:leave', '2026-11-30 18:05:00', None),
    ('admin', 1, 'time', 'Time correction · Kasun Jayawardena', 'Tue 1 Dec · Out 2:10 PM', 'approvals:time', '2026-12-01 19:00:00', None),
    ('admin', 1, 'chat', 'Shalini Rajan', 'Good morning Madam. I will be 15 minutes late today due to traffic.', 'chat:s3', '2026-12-02 07:12:00', None),
    ('admin', 1, 'chat', STAFF[6], 'The Final Year concert costumes have arrived.', 'chat:s6', '2026-12-02 09:40:00', None),
    ('admin', 1, 'sleave', 'Child leave · Kavin Perera', 'Fri 4 Dec · Leave early 10:30 AM · Dentist appointment', 'approvals:sleave', '2026-12-01 20:10:00', None),
]
ins('app_notifications', [dict(id=i + 1, to_kind=a, to_id=b, topic=c, title=d, body=e, view=f, created_at=g, read_at=h, pushed=1) for i, (a, b, c, d, e, f, g, h) in enumerate(N)])

# ---------------- read state (what is still "new") ----------------
R = [('staff', 1, 's1', last_s[1]), ('staff', 1, 'all', a2), ('staff', 1, 'p1', 3),
     ('admin', 1, 's1', last_s[1]), ('admin', 1, 's4', last_s[4]), ('admin', 1, 's3', 0), ('admin', 1, 's6', [m['id'] for m in M if m['thread'] == 's6'][-2]),
     ('par', 1, 't1', t1_read + 1), ('par', 1, 't2', len(PM)), ('par', 1, 't6', t6_read), ('par', 1, 'posts', 3)]
ins('app_chat_reads', [dict(kind=a, owner_id=b, thread=c, last_id=d) for a, b, c, d in R])
open('chats.sql', 'w').write('\n'.join(out) + '\n')
print('chats.sql', len(M), 'staff msgs', len(PM), 'parent msgs')
