from pathlib import Path
import json, html, textwrap
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, KeepTogether
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas

ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'output'
P=OUT/'pdf'
PURPLE='#482454'; ORANGE='#EF7934'; INK='#252238'; MUTED='#655F70'; PALE='#F5F1F7'
def f(id,src,label,kind='text',options=None,show=None):
    return dict(id=id,source=src,label=label,kind=kind,options=options or [],show=show)
YN=['Yes','No']
sections=[
 dict(title='Survey & disability',subtitle='Start a new field survey',fields=[
 f('F01','Header','Survey date','date'),
 f('F02','Header','Type of disability','multi',['Blindness (Blind)','Low vision (LV)','Hard of hearing (HoH)','Deafness (Deaf)','Cerebral palsy (CP)','Locomotor disability (LCD)','Autism (ASD)','Intellectual disability (ID)','Multiple disabilities (MI)','Other']),
 f('F03','Header','Other disability - specify',show=['F02','Other'])]),
 dict(title='Personal details',subtitle='Identity of the person being surveyed',fields=[
 f('F04','1','Full name'),f('F05','5','Date of birth','date'),f('F06','2','Age (years)','number'),f('F07','6','Gender','select',['Male','Female','Other'])]),
 dict(title='Contact & community',subtitle='Contact and background information',fields=[
 f('F08','3','Full address','textarea'),f('F09','4','Contact number','tel'),f('F10','7','Caste category','select',['Scheduled Caste (SC)','Scheduled Tribe (ST)','Other Backward Classes (OBC)','General']),f('F11','8','Language')]),
 dict(title='Family & livelihood',subtitle='Household circumstances',fields=[
 f('F12','9','Is there another person with a disability in the family?','radio',YN),f('F13','9 follow-up','If yes, please specify',show=['F12','Yes']),f('F14','13','Annual family income','number'),f('F15','14 (family)','Family occupation')]),
 dict(title='Disability & education',subtitle='Background and educational attainment',fields=[
 f('F16','10','Cause of disability','textarea'),f('F17','11','Time of onset of disability','select',['Before birth','At birth','After birth']),f('F18','12','Educational qualification','select',['No formal education','Primary','Secondary','Higher secondary','Other'])]),
 dict(title='Health information',subtitle='Seizures and other illnesses',fields=[
 f('F19','14 (health)','Does the person have epileptic seizures?','radio',YN),f('F20','15','If yes, does the person take medication?','radio',YN,show=['F19','Yes']),f('F21','16','Does the person have any other illness?','radio',YN)]),
 dict(title='Treatment & support',subtitle='Medical treatment and assistive devices',fields=[
 f('F22','17','Has any other medical treatment been received?','radio',YN),f('F23','17 follow-up','If yes, provide treatment details','textarea',show=['F22','Yes']),f('F24','18','Has the person received any assistive device?','radio',YN),f('F25','18 follow-up','If yes, name the device',show=['F24','Yes'])]),
 dict(title='Children’s education',subtitle='Attendance, classes and training',fields=[
 f('F26','19','Does the child attend an Anganwadi centre?','radio',YN),f('F27','20','Is the child currently studying at school?','radio',YN),f('F28','21','Class / grade'),f('F29','22','Is the person undertaking vocational training / a course?','radio',YN),f('F30','23','Has the person received any other education / training?','radio',YN)]),
 dict(title='Available documents',subtitle='Documents available for government schemes',fields=[
 f('F31','Document 1','Disability certificate','check'),f('F32','Document 2','Caste certificate','check'),f('F33','Document 3','Bank account details','check'),f('F34','Document 4','Aadhaar card','check'),f('F35','Document 5','Ration card','check'),f('F36','Document 6','Voter identity card','check'),f('F37','Document 7','Birth certificate','check'),f('F38','Document 8','Unique Disability ID (UDID)','check')]),
 dict(title='Declaration & signatures',subtitle='Confirm the information with the respondent',fields=[
 f('F39','Declaration','Signature of the person with a disability / family member','signature'),f('F40','Declaration','Field worker’s signature','signature')])
]
fields=[x for s in sections for x in s['fields']]
declaration='I declare that the information provided above is correct to the best of my knowledge and has been provided with my consent.'
styles=getSampleStyleSheet()
styles.add(ParagraphStyle(name='TitleX',fontName='Helvetica-Bold',fontSize=27,leading=32,textColor=colors.HexColor(PURPLE),spaceAfter=16))
styles.add(ParagraphStyle(name='HeadX',fontName='Helvetica-Bold',fontSize=15,leading=20,textColor=colors.HexColor(PURPLE),spaceBefore=15,spaceAfter=9))
styles.add(ParagraphStyle(name='BodyX',fontSize=10,leading=15,textColor=colors.HexColor(INK),spaceAfter=8))
styles.add(ParagraphStyle(name='SmallX',fontSize=8,leading=11,textColor=colors.HexColor(MUTED),spaceAfter=5))
def para(t,sty='BodyX'):return Paragraph(html.escape(t).replace('\n','<br/>'),styles[sty])
def footer(c,d):
    c.setStrokeColor(colors.HexColor('#E4DDE7'));c.line(42,37,A4[0]-42,37)
    c.setFont('Helvetica',8);c.setFillColor(colors.HexColor(MUTED));c.drawString(42,24,'SENSE INDIA  /  MOBILE SURVEY PLANNING  /  22 OCT 2026');c.drawRightString(A4[0]-42,24,str(d.page))
def doc(path,story):
    SimpleDocTemplate(str(path),pagesize=A4,rightMargin=42,leftMargin=42,topMargin=42,bottomMargin=52).build(story,onFirstPage=footer,onLaterPages=footer)
def title(k,t,sub):return [para(k.upper(),'SmallX'),para(t,'TitleX'),para(sub),Spacer(1,9)]
def table(rows,widths):
    t=Table([[para(str(c),'SmallX') for c in r] for r in rows],colWidths=widths,repeatRows=1,hAlign='LEFT')
    t.setStyle(TableStyle([('BACKGROUND',(0,0),(-1,0),colors.HexColor(PALE)),('VALIGN',(0,0),(-1,-1),'TOP'),('BOTTOMPADDING',(0,0),(-1,-1),7),('TOPPADDING',(0,0),(-1,-1),7),('LINEBELOW',(0,0),(-1,-1),.35,colors.HexColor('#E5DFE8'))]))
    return t

styles['BodyX'].fontSize=9.5
styles['BodyX'].leading=13
styles['BodyX'].spaceAfter=6
story=title('01 / English translation','Survey form','Sense International India, Ahmedabad\nSparsh Centre, Sanand')
story += [para('English working translation | Source: supplied two-page Hindi survey. The source question references are retained below, including its duplicate question 14. Empty lines are for responses. This is a translated form, not a completed survey.','SmallX')]
original_groups=[('Survey details',[fields[0],fields[1],fields[2]]),('Personal information',[next(f for f in fields if f['id']==i) for i in ['F04','F06','F08','F09','F05','F07','F10','F11','F12','F13']]),('Educational information (source heading)',[next(f for f in fields if f['id']==i) for i in ['F16','F17','F18','F14','F15']]),('Health information',[next(f for f in fields if f['id']==i) for i in ['F19','F20','F21','F22','F23','F24','F25']]),('Children’s education',[next(f for f in fields if f['id']==i) for i in ['F26','F27','F28','F29','F30']]),('Documents available for government schemes',[f for f in fields if f['kind']=='check'])]
for name,fs in original_groups:
    story.append(para(name,'HeadX'))
    for x in fs:
        ref='' if x['source'].startswith(('Header','Document')) else x['source']+'. '
        content=ref+x['label']
        if x['options']:content+=': '+ '  /  '.join(x['options'])
        elif x['kind']=='check':content='[  ] '+content
        else:content+=': __________________________________'
        story.append(para(content))
story += [para('Declaration','HeadX'),para(declaration),para('Signature of the person with a disability / family member: ____________________'),para('Field worker’s signature: ____________________'),para('Translation and source notes','HeadX')]
notes=[
 'The English markers “The end” and “New section” are editing notes in the source. They are not survey questions or instructions to the project team and are omitted from the translated form.',
 'Source question 14 appears twice: family occupation and epileptic seizures. References distinguish “14 (family)” and “14 (health)”; the app uses unique field IDs.',
 '“HoH” is rendered as “hard of hearing”; the Hindi wording is colloquial. “MI” is retained as printed for multiple disabilities; confirm the preferred abbreviation before release. “LCD” is also retained as printed.',
 '“No formal education” is a respectful rendering of the source option meaning “uneducated”. The source offers “Other” for educational qualification without a follow-up text field.',
 'UDID is expanded as “Unique Disability ID”. Anganwadi refers to the local early-childhood care and education centre; the term is retained.',
 'The source does not specify required fields, currency, disability selection limits, adult applicability rules or document uploads. Proposed app behaviour is documented separately.'
]
story += [para(n,'SmallX') for n in notes]
doc(P/'01_English_Survey_Form.pdf',story)
styles['BodyX'].fontSize=10
styles['BodyX'].leading=15
styles['BodyX'].spaceAfter=8

# Static design review: every source field is visible, including all conditional fields.
c=canvas.Canvas(str(P/'02_Mobile_App_Mockups.pdf'),pagesize=A4)
W,H=A4
def text(x,y,t,size=10,color=INK,bold=False):
    c.setFont('Helvetica-Bold' if bold else 'Helvetica',size);c.setFillColor(colors.HexColor(color));c.drawString(x,y,t)
def lines(t,width,size=10):
    words=t.split(); out=[]; line=''
    for word in words:
        n=(line+' '+word).strip()
        if c.stringWidth(n,'Helvetica',size)>width and line:out.append(line);line=word
        else:line=n
    return out+[line]
def wrap(t,x,y,width,size=10,color=INK,bold=False):
    for line in lines(t,width,size):text(x,y,line,size,color,bold);y-=size*1.35
    return y
def roundbox(x,y,w,h,fill,stroke='#E2D9E7',r=9):
    c.setFillColor(colors.HexColor(fill));c.setStrokeColor(colors.HexColor(stroke));c.roundRect(x,y,w,h,r,fill=1,stroke=1)
for idx,s in enumerate(sections+[dict(title='Review & submit',subtitle='Check each section before sending',fields=[])]):
    text(35,H-35,'02 / MOBILE APP CONCEPT',9,PURPLE,True)
    text(35,H-64,f'{idx+1:02d}  {s["title"].replace("’",chr(39))}',21,PURPLE,True)
    text(35,H-85,'All values are blank. Conditional follow-ups are expanded for design review.',9,MUTED)
    px,py,pw,ph=35,70,330,650
    roundbox(px,py,pw,ph,'#FFFFFF',PURPLE,24)
    text(px+20,py+ph-24,'9:41',10,INK,True);text(px+pw-85,py+ph-24,'4G  100%',9)
    text(px+20,py+ph-56,'Sparsh',19,PURPLE,True);text(px+205,py+ph-53,'FIELD SURVEY',8,MUTED)
    c.setFillColor(colors.HexColor('#EEE7F1'));c.rect(px+20,py+ph-77,pw-40,4,fill=1,stroke=0)
    c.setFillColor(colors.HexColor(ORANGE));c.rect(px+20,py+ph-77,(pw-40)*(idx+1)/11,4,fill=1,stroke=0)
    text(px+20,py+ph-98,f'STEP {idx+1} OF 11',8,PURPLE,True)
    y=wrap(s['title'].replace('’',"'"),px+20,py+ph-128,pw-40,19,PURPLE,True)-3
    y=wrap(s['subtitle'],px+20,y,pw-40,9,MUTED)-15
    if idx==9:
        y=wrap(declaration,px+20,y,pw-40,10)-14
    for x in s['fields']:
        lab=x['label'].replace('’',"'")
        if x['kind']=='check':
            roundbox(px+20,y-15,18,18,'#FFFFFF',r=3);wrap(lab,px+48,y-2,pw-73,10);y-=37;continue
        y=wrap(lab,px+20,y,pw-40,10,INK,True)-5
        if x['kind']=='multi':
            for opt in x['options']:
                roundbox(px+20,y-10,13,13,'#FFFFFF',r=2);text(px+43,y-7,opt,10);y-=24
            y-=5
        elif x['kind']=='radio':
            for j,opt in enumerate(x['options']):
                roundbox(px+20+j*140,y-27,130,34,'#FAF8FC');text(px+33+j*140,y-15,'o  '+opt,10)
            y-=48
        elif x['kind']=='signature':
            roundbox(px+20,y-70,pw-40,77,'#FAF8FC');text(px+33,y-23,'Tap to capture signature',10,MUTED);text(px+33,y-51,'Clear / Redraw',8,PURPLE);y-=91
        else:
            h=52 if x['kind']=='textarea' else 37
            roundbox(px+20,y-h,pw-40,h,'#FAF8FC')
            hint='Select an option' if x['kind']=='select' else 'DD / MM / YYYY' if x['kind']=='date' else 'Enter response'
            text(px+31,y-23,hint,10,MUTED);y-=h+18
    if idx==10:
        for j,sec in enumerate(sections):
            text(px+20,y,sec['title'].replace('’',"'"),10);text(px+pw-53,y,'Edit',9,PURPLE);y-=29
        y=wrap('Submission is a demonstration only. No information is sent.',px+20,y-7,pw-40,10,MUTED)
    roundbox(px+20,py+18,87,40,'#FFFFFF');text(px+42,py+33,'Back',11,PURPLE)
    roundbox(px+118,py+18,pw-138,40,PURPLE,PURPLE);text(px+140,py+33,'Submit survey' if idx==10 else 'Continue',11,'#FFFFFF',True)
    sx=389;sy=py+ph-10
    sy=wrap('SCREEN NOTES',sx,sy,168,10,PURPLE,True)-12
    mapping='Source fields: '+(', '.join(x['id'] for x in s['fields']) or 'All F01-F40')
    sy=wrap(mapping,sx,sy,168,9)-14
    if idx==0:note='Proposed multi-select disability list. “Other” reveals its text field. Confirm selection rules with the programme owner.'
    elif idx==1:note='Keep age and date of birth as separate source fields. Confirm how unknown birth dates and approximate ages will be recorded.'
    elif idx==2:note='A contact number is a text value, preserving + and leading zeros. Full address remains one field, as in the source.'
    elif idx==3:note='The family follow-up appears only for Yes. Currency is not stated in the source; confirm INR before adding a currency label.'
    elif idx==4:note='The source groups these under educational information. The app uses a clearer heading. No additional “Other qualification” field is assumed.'
    elif idx==5:note='Medication follows Yes to seizures. “Other illness” is a Yes/No question only; the source has no illness-details field.'
    elif idx==6:note='Treatment details and device name appear only when their parent response is Yes. Both are expanded here for coverage.'
    elif idx==7:note='Retain class/grade and all education questions. Adult applicability and whether class should depend on school attendance need approval.'
    elif idx==8:note='Checkboxes indicate documents available. Do not collect document numbers, images or uploads without a separately approved requirement.'
    elif idx==9:note='Preserve the source declaration. Capture both signatures, with clear/redraw and an accessible alternative to be agreed before development.'
    else:note='Proposed app step. Review and edit all sections. A production build needs agreed validation, reliable saving, and a clear submission receipt.'
    sy=wrap(note,sx,sy,168,10)-20
    sy=wrap('DESIGN DIRECTION',sx,sy,168,10,PURPLE,True)-10
    sy=wrap('Purple and orange inspired by the source identity; this is a proposed visual direction, not an approved brand specification. Large controls, clear labels and one-column forms.',sx,sy,168,9)-16
    wrap('Concept only. Offline storage, accounts, backend, security controls and final validation are implementation work.',sx,sy,168,9,MUTED)
    text(35,35,'SENSE INDIA / DESIGN REVIEW / SOURCE-TRACEABLE FIELDS',8,MUTED);text(W-65,35,str(idx+1),8,MUTED)
    c.showPage()
c.save()

# A single shared field model drives both the interactive mockup and the register.
(ROOT/'work'/'survey_schema.json').write_text(json.dumps(sections,ensure_ascii=False,indent=2))
register=['# Field register and implementation notes','', 'Source: supplied two-page Hindi survey. Stable IDs distinguish the duplicate question 14. All 40 fields, including conditional text and two signatures, are represented in the mockup. Checkbox choices are stored as eight document-availability fields.','', '| ID | Source reference | English label | Control | Visibility / rule |','|---|---|---|---|---|']
for x in fields:
    rule=f"Show if {x['show'][0]} includes/is {x['show'][1]}" if x['show'] else 'Always visible in its section'
    register.append('| '+' | '.join([x['id'],x['source'],x['label'],x['kind'],rule])+' |')
register += ['', '## Source options','']
for x in fields:
    if x['options']:register.append(f"- {x['id']}: {'; '.join(x['options'])}.")
register += ['', '## Declaration',declaration,'','## Decisions required before development', *['- '+n for n in notes[1:]],'- Confirm required fields and unknown/not applicable responses; source blanks do not establish mandatory status.','- Keep class/grade visible until applicability rules are approved. Do not exclude adults automatically.','- Confirm income currency, precision and whether income may be unknown.','- For changing a parent answer, confirm clearing versus retaining hidden follow-up answers. Never submit stale hidden values silently.','- Confirm whether age is calculated from date of birth or entered independently; avoid blocking people with approximate dates.','- Agree respondent/family-member signing authority, accessible signature alternatives and the programme’s consent process. The existing declaration is not a complete digital consent specification.']
(OUT/'Field_Register.md').write_text('\n'.join(register))

tasks=[
 ('PM1','Project manager','Discovery & scope','1.1 Walk through the form with field staff; 1.2 confirm population, languages, devices and connectivity; 1.3 agree MVP, exclusions and measurable pilot goals.','None','Approved scope, user journey and stakeholder list; all source fields accounted for.','2-3'),
 ('PM2','Project manager','Resolve source decisions','2.1 Confirm duplicate numbering and disability labels; 2.2 decide selection limits and mandatory fields; 2.3 approve age/DOB, income and adult applicability; 2.4 approve declaration and signature process.','PM1','Signed field register and decision log; no unresolved launch-blocking rules.','2-3'),
 ('PM3','Project manager','Plan & control delivery','3.1 Build backlog and milestones; 3.2 assign owners; 3.3 maintain risks, dependencies and change log; 3.4 run sprint demos and acceptance reviews.','PM1','Prioritised backlog, estimates and weekly review cadence.','3-5 across project'),
 ('PM4','Project manager','Data governance & operations','4.1 Identify data owner and permitted roles; 4.2 agree collection, access, retention, deletion and export needs; 4.3 approve hosting and operational support; 4.4 obtain appropriate organisational review.','PM2','Approved data handling and support plan covering health, caste and signatures.','2-3'),
 ('PM5','Project manager','Pilot & release coordination','5.1 Recruit representative field users; 5.2 prepare training; 5.3 define pilot entry/exit; 5.4 triage feedback; 5.5 secure business sign-off and handover.','QA4','Pilot acceptance, release checklist and named support owner.','3-4'),
 ('DS1','Designer','Research & information architecture','1.1 Interview field workers; 1.2 map survey sequence; 1.3 organise all F01-F40; 1.4 map conditional branches and review paths.','PM1','Complete flow with every field and both signatures.','2-3'),
 ('DS2','Designer','Visual design & components','2.1 Confirm brand; 2.2 specify typography, spacing and touch controls; 2.3 design selectors, checkboxes, signatures and errors; 2.4 define responsive layouts.','DS1','Approved screen designs and reusable component specifications.','3-4'),
 ('DS3','Designer','Full interaction states','3.1 Design blank/filled/error forms; 3.2 parent answer changes; 3.3 drafts and resume; 3.4 offline/sync failures if adopted; 3.5 review, edit and receipt; 3.6 signature clear/redraw and alternative.','DS2, PM2','Annotated prototype includes validation, branching and failure recovery.','2-3'),
 ('DS4','Designer','Accessibility & handoff','4.1 Check screen-reader labels and focus order; 4.2 test large text and contrast; 4.3 test with field users; 4.4 deliver assets, copy and specifications.','DS3','Usability issues resolved; developer-ready handoff and accessibility checklist.','2-3'),
 ('AD1','App developer','Architecture & project setup','1.1 Select platform after device review; 1.2 establish environments and build pipeline; 1.3 define survey schema and API contract; 1.4 identify backend responsibility.','PM2, PM4, DS1','Build runs on target devices; architecture and data model reviewed.','3-4'),
 ('AD2','App developer','Survey foundation','2.1 Implement navigation; 2.2 model all F01-F40; 2.3 build inputs and selectors; 2.4 implement review/edit; 2.5 preserve entries on navigation.','AD1, DS2','All fields and options implemented; no lost entries when moving between steps.','4-6'),
 ('AD3','App developer','Rules & validation','3.1 Add conditional fields; 3.2 handle parent changes; 3.3 implement approved required rules; 3.4 check dates, ages, phone and income; 3.5 cover class/adult applicability as approved.','AD2, PM2','Approved rules pass unit/component tests; hidden stale answers are excluded or explicitly resolved.','3-4'),
 ('AD4','App developer','Signatures & finalisation','4.1 Capture two signatures; 4.2 support clear/redraw; 4.3 implement agreed accessible alternative; 4.4 bind declaration to survey version; 4.5 implement submission result.','AD2, PM2, DS3','Both signatures are associated with the correct survey and declaration version.','2-3'),
 ('AD5','App developer + backend owner','Storage, API & synchronisation','5.1 Build save/read/update endpoints; 5.2 implement drafts and secure local storage; 5.3 queue/retry offline submissions if adopted; 5.4 prevent duplicate submits; 5.5 define conflict handling and receipts.','AD1, PM4','Saved data survives app restart; retry is idempotent; failures are recoverable. Backend ownership must be assigned.','6-9'),
 ('AD6','App developer + backend owner','Access & data protection','6.1 Implement approved login and permissions; 6.2 protect transport/storage; 6.3 remove sensitive logs; 6.4 apply retention/deletion; 6.5 implement agreed export with access checks.','AD1, PM4','Unauthorised access fails; sensitive fields and signatures do not appear in logs or unapproved exports.','3-5'),
 ('AD7','App developer','Release & handover','7.1 Fix pilot defects; 7.2 prepare release builds; 7.3 configure monitoring without sensitive payloads; 7.4 document support and rollback; 7.5 distribute through approved channel.','QA4, PM5','Accepted production build, release notes and operational handover.','2-3'),
 ('QA1','Testing team','Test strategy & traceability','1.1 Map F01-F40 to cases; 1.2 define device/OS matrix; 1.3 prepare synthetic data; 1.4 agree severity, acceptance and pilot exit criteria.','PM2, DS1','Approved test plan with every field, option and condition mapped.','2-3'),
 ('QA2','Testing team','Functional & rule testing','2.1 Test inputs and every option; 2.2 verify all five conditional branches; 2.3 test Back/Continue and review edits; 2.4 test both signatures; 2.5 check all approved validation boundaries.','AD2-AD4','All mandatory cases pass; no missing fields, swapped mappings or lost answers.','4-5'),
 ('QA3','Testing team','Reliability, accessibility & access','3.1 Test interruption/restart; 3.2 offline/retry/duplicates if adopted; 3.3 test permissions and sensitive logs; 3.4 screen readers, large text and contrast; 3.5 device performance and slow networks.','AD5, AD6, DS4','Critical access, data loss and accessibility defects resolved; target devices pass.','4-6'),
 ('QA4','Testing team','Regression, pilot & release evidence','4.1 Run end-to-end regression; 4.2 support field pilot; 4.3 retest defects; 4.4 validate exported data if in scope; 4.5 publish test summary and recommend release readiness.','QA2, QA3','No open critical/high defects; agreed lower-severity exceptions recorded; business acceptance supported by evidence.','3-4')
]
md=['# Sense India mobile survey - project delivery plan','','Prepared 22 October 2026. Planning baseline derived from the supplied form; estimates are provisional person-days, not a fixed-price quote. This is a design and planning package, not a production application.','','## Outcome and scope','Deliver an English mobile survey covering all 40 source fields, every source option, five conditional follow-ups, the original declaration and both signatures. Provide review/edit and a confirmed submission outcome.','', 'Source fields are baseline requirements. Login, local drafts, offline synchronisation, backend, roles, exports and release monitoring are proposed implementation scope and need explicit prioritisation. Document uploads, document numbers, GPS, photos, medical advice, eligibility decisions and scheme applications are outside the form and excluded unless separately approved.','','## Role-based work breakdown','']
for tid,role,name,sub,dep,accept,effort in tasks:
    md += [f'### {tid} | {role} | {name}',f'**Effort:** {effort} person-days. **Dependencies:** {dep}.','']
    md += ['- '+x.strip()+'.' for x in sub.split('; ')]
    md += ['',f'**Deliverable / acceptance:** {accept}','']
md += ['## Indicative schedule and gates','Assumption: one PM (part time), one designer, one app developer, one named backend owner and one tester. A cross-platform mobile build is assumed for estimating only; choose the platform after confirming devices. Backend effort is included in the developer stream estimates, not an extra allowance. Design and QA overlap development.','','| Window | Work and exit gate |','|---|---|','| Week 1 | Discovery, field decisions and data handling. Gate: approve scope and field register. |','| Week 2 | Detailed design, usability checks, architecture and test plan. Gate: approved design and API contract. |','| Weeks 3-5 | Build survey, signatures, draft/API and any approved offline flow; continuous QA. Gate: feature-complete pilot candidate. |','| Week 6 | Accessibility, access, reliability and regression. Gate: no critical/high defects. |','| Week 7 | Field pilot, fixes and training. Gate: programme owner acceptance. |','| Week 8 | Contingency, release and operational handover. Gate: supported release. |','','Indicative effort by stream: PM 12-18 days; design 9-13; app/backend 23-34; testing 13-18; total 57-83 person-days before contingency. Reserve 15-20% contingency. Calendar duration depends on staffing and stakeholder turnaround; the eight-week outline is a planning target. If one developer owns both client and backend, allow roughly 9-11 weeks or reduce approved scope, subject to re-estimation.','','## Quality and acceptance examples','- Confirm disability options exactly match the approved register, including Other and its follow-up.','- Test F12 Yes -> enter F13 -> change to No; no stale hidden answer is silently submitted. Repeat for F19/F20, F22/F23 and F24/F25.','- Test both health and family question 14 mappings; they must remain separate fields.','- Age and DOB: future DOB, leap day, unknown DOB and inconsistent entered age follow the approved policy.','- Phone retains leading zeros and +; income accepts the approved units and range.','- Each document checkbox is independent; no document image or number is collected.','- Both signatures can be captured, cleared and redrawn; the agreed accessible alternative is testable.','- Back, Continue, review and edit preserve entries. If persistence is adopted, app termination and resume preserve approved drafts securely.','- If offline submission is adopted, retry after timeout creates one server record and produces a stable receipt.','- Test screen-reader reading order and labels, large text without clipping, and approximately 44-48 logical-pixel touch targets on target devices.','- Production release requires approved access controls and data handling for health, caste, contact details and signatures.','','## Risks and decisions','- The source is a discussion draft. Resolve the abbreviation MI, duplicate numbering, multi-select rules and applicability before coding.','- Unknown ages, inability to sign and unanswered questions need inclusive recording rules. Do not invent forced answers.','- Poor field connectivity may make offline storage essential; validate this in discovery because it affects architecture and estimates.','- A mobile developer alone does not establish a production backend. Assign backend, hosting and support ownership before committing a date.','- Sensitive data collection requires an approved organisational process; this package does not determine legal requirements.','- Review whether family-member signing needs relationship/name fields. These are not in the source and require a scope change.','','## Traceability and handover','Use Field_Register.md for F01-F40, source references and options. The mockup screens follow the same IDs. The PDF translation retains source grouping and numbering; the mobile concept reorganises the questions for a shorter, clearer flow.','', 'Handover pack: approved field register and decision log, final designs and states, backlog, API/schema, source code/build instructions, test evidence, pilot sign-off, training material and support/retention instructions.']
(OUT/'Project_Delivery_Plan.md').write_text('\n'.join(md))
story=title('03 / Project delivery plan','From survey to mobile app','Role-based work breakdown, dependencies, acceptance criteria and an indicative delivery schedule.')
task_group=[]
schedule_rows=[]
def flush_task():
    if task_group:
        story.append(KeepTogether(task_group[:]))
        task_group.clear()
def flush_schedule():
    if schedule_rows:
        story.append(table(schedule_rows[:],[88,423]))
        story.append(Spacer(1,12))
        schedule_rows.clear()
for line in md[2:]:
    if not line:continue
    if line.startswith('|'):
        flush_task()
        if not line.startswith('|---'):
            schedule_rows.append([v.strip() for v in line.strip('|').split('|')])
        continue
    flush_schedule()
    if line.startswith('### '):
        flush_task()
        task_group.append(para(line[4:],'HeadX'))
    elif line.startswith('## '):
        flush_task()
        story.append(para(line[3:],'HeadX'))
    elif task_group:
        task_group.append(para(line.replace('**','')))
    else:story.append(para(line.replace('**','')))
flush_task()
flush_schedule()
story += [PageBreak(),para('Field register - complete source coverage','TitleX'),para('Source reference numbers are preserved, including the duplicate 14. All conditional fields appear in the design review mockups.','SmallX'),table([['ID / source','English field','Control / visibility']]+[[x['id']+' / '+x['source'],x['label'],x['kind']+(' / if '+x['show'][0]+' = '+x['show'][1] if x['show'] else '')] for x in fields],[85,255,171])]
doc(P/'03_Project_Delivery_Plan.pdf',story)
print('Generated 3 PDFs, field register, project plan and shared schema. Source field count:',len(fields))
