#!/usr/bin/env python3
"""Build the vertical-slice plan from tools/definitions/slices_def.py and the domain specifications.

Writes  delivery/slices.md, delivery/slices/<FLOW>.md, data/slices.csv   (under docs/implementation_plan)
Run:    python3 docs/implementation_plan/tools/build_slices.py   (after tools/extract.py)
Fails if a functional requirement is unassigned, assigned twice or unknown, or if a slice
depends on a slice released in a later phase.
"""
import re, os, glob, csv, collections, sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, 'definitions'))
sys.dont_write_bytecode = True
from slices_def import FLOWS, SLICES, PHASES, PHASE_NOTES  # noqa: E402

PLAN = os.path.dirname(HERE)
SPECS = os.path.join(os.path.dirname(PLAN), 'domain_specs')
ABBR = ['ADM', 'ISE', 'CLI', 'ANC', 'FIN', 'HIM', 'PEX', 'ANL', 'EBP', 'ESS']
FOLDER = {a: f'D{i + 1:02d}-{a}' for i, a in enumerate(ABBR)}
NUM = {a: i + 1 for i, a in enumerate(ABBR)}
GENERATED = '<!-- Generated by tools/build_slices.py from tools/definitions/slices_def.py and docs/domain_specs. Edit slices_def.py, not this file. -->'


def plain(t):
    t = re.sub(r'<a id="[^"]+"></a>', '', t)
    return re.sub(r'\[([^\]\[]+)\]\([^)\s]+\)', r'\1', t)


def ab_of(i):
    return re.match(r'[A-Z]+-([A-Z]{3})-', i).group(1)


def td(t):
    return t.replace('|', '\\|')


# ------------------------------------------------------------------ load specification data
FR = {}
for r in csv.DictReader(open(os.path.join(PLAN, 'data', 'backlog.csv'))):
    FR[r['requirement_id']] = dict(id=r['requirement_id'], ab=r['domain'], title=r['title'], priority=r['priority'], mod=r['module_id'],
                                   up_mods=r['needs_modules'].split(), decs=r['open_decisions'].split(), wfs=[])
MODFILE, MODNAME, MODFRS = {}, {}, collections.defaultdict(list)
for ab in ABBR:
    for p in glob.glob(os.path.join(SPECS, FOLDER[ab], '05-functional-requirements', 'MOD-*.md')):
        mid = re.match(r'(MOD-[A-Z]+-\d{3})', os.path.basename(p)).group(1)
        MODFILE[mid] = os.path.basename(p)
        raw = open(p).read()
        MODNAME[mid] = re.search(r'^## 5\.\d+ Module Specification: (.*)$', raw, re.M).group(1).strip()
        for b in re.split(r'^(?=#### Requirement )', raw, flags=re.M)[1:]:
            fid = re.match(r'#### Requirement (FR-[A-Z0-9-]+):', b).group(1)
            m = re.search(r'^\| Related Workflow \| (.*?) \|$', plain(b), re.M)
            FR[fid]['wfs'] = re.findall(r'WF-[A-Z]{3}-\d{3}', m.group(1)) if m else []
            MODFRS[mid].append(fid)
WF, TESTS = {}, []
for ab in ABBR:
    t = open(os.path.join(SPECS, FOLDER[ab], '04-processes-and-workflows.md')).read()
    for m in re.finditer(r'^### Workflow (WF-[A-Z]{3}-\d{3}): (.*)$', t, re.M):
        WF[m.group(1)] = m.group(2).strip()
    t = open(os.path.join(SPECS, FOLDER[ab], '15-testing.md')).read()
    for row in re.findall(r'^\| <a id="test-[^\n]*$', t, re.M):
        c = [plain(x).strip() for x in row.strip().strip('|').split('|')]
        TESTS.append(dict(id=c[0], ab=ab, frs=re.findall(r'FR-[A-Z]{3}-[A-Z]{2,4}-\d{3}', c[1]), type=c[3] if len(c) > 3 else ''))
DEC = {r['decision_id']: r for r in csv.DictReader(open(os.path.join(PLAN, 'data', 'decisions.csv')))}

# ------------------------------------------------------------------ expand and validate slices
BY = {}
assigned = {}
errors = []
for s in SLICES:
    s['flow'] = s['id'].split('-')[0]
    s['frs'] = []
    for line in s['reqs']:
        ab, codes = line.split(':')
        for code in [c.strip() for c in codes.split(',')]:
            fid = f'FR-{ab.strip()}-{code}'
            if fid not in FR:
                errors.append(f'{s["id"]}: unknown requirement {fid}')
            elif fid in assigned:
                errors.append(f'{fid} assigned to both {assigned[fid]} and {s["id"]}')
            else:
                assigned[fid] = s['id']
                s['frs'].append(fid)
    BY[s['id']] = s
errors += [f'unassigned requirement {f} ({FR[f]["title"]})' for f in FR if f not in assigned]
for s in SLICES:
    for a in s['after']:
        if a not in BY:
            errors.append(f'{s["id"]}: unknown predecessor {a}')
        elif BY[a]['phase'] > s['phase']:
            errors.append(f'{s["id"]} (phase {s["phase"]}) depends on {a} (phase {BY[a]["phase"]})')
if errors:
    print('\n'.join(errors))
    sys.exit(1)


def ancestors(sid, seen=None):
    seen = seen if seen is not None else set()
    for a in BY[sid]['after']:
        if a not in seen:
            seen.add(a)
            ancestors(a, seen)
    return seen


ORDER = [s['id'] for s in SLICES]
for s in SLICES:
    s['anc'] = ancestors(s['id'])
    s['doms'] = sorted({FR[f]['ab'] for f in s['frs']}, key=lambda a: NUM[a])
    s['prio'] = collections.Counter(FR[f]['priority'] for f in s['frs'])
    # module dependencies not satisfied by order: the needed module has no requirement in this slice or an earlier one
    gaps = collections.defaultdict(list)
    for f in s['frs']:
        for m in FR[f]['up_mods']:
            if not any(assigned[x] == s['id'] or assigned[x] in s['anc'] for x in MODFRS[m]):
                gaps[m].append(f)
    s['gaps'] = gaps
    s['decs'] = sorted({d for f in s['frs'] if FR[f]['priority'] == 'Must' for d in FR[f]['decs'] if DEC.get(d, {}).get('class') == 'A'})  # resolved decisions have class R and drop out
    s['wfs'], s['tests'] = [], collections.Counter()
# a workflow gates the slice that holds most of the requirements citing it (earliest slice on a tie)
forced = {w: s['id'] for s in SLICES for w in s.get('gate_wfs', [])}
for w, sid in forced.items():
    assert w in WF, w
    BY[sid]['wfs'].append(w)
for w in WF:
    if w in forced:
        continue
    c = collections.Counter(assigned[f] for f in FR if w in FR[f]['wfs'])
    if c:
        best = max(c, key=lambda k: (c[k], -ORDER.index(k)))
        BY[best]['wfs'].append(w)
unplaced_wf = [w for w in WF if not any(w in s['wfs'] for s in SLICES)]
untraced_tests = 0
for t in TESTS:
    sl = [assigned[f] for f in t['frs'] if f in assigned]
    if sl:
        BY[sl[0]]['tests'][t['ab']] += 1
    else:
        untraced_tests += 1


# ------------------------------------------------------------------ output helpers
def spec(depth, ab, rel, anchor=None):
    return '../' * (depth + 1) + f'domain_specs/{FOLDER[ab]}/{rel}' + (f'#{anchor}' if anchor else '')


def L(i, depth):
    ab, t = ab_of(i), i.split('-')[0]
    if t == 'FR':
        return f'[{i}]({spec(depth, ab, "05-functional-requirements/" + MODFILE[FR[i]["mod"]], i.lower())})'
    if t == 'MOD':
        return f'[{i}]({spec(depth, ab, "05-functional-requirements/" + MODFILE[i])})'
    rel = {'DEC': '18-assumptions-decisions-gaps.md', 'WF': '04-processes-and-workflows.md'}[t]
    return f'[{i}]({spec(depth, ab, rel, i.lower())})'


def SL(sid, depth):
    pre = '' if depth == 2 else 'slices/'
    return f'[{sid}]({pre}{BY[sid]["flow"]}.md#{sid.lower()})'


def write(rel, lines):
    path = os.path.join(PLAN, rel)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    open(path, 'w').write('\n'.join(lines).rstrip('\n') + '\n')


FLOWNAME = {f[0]: f[1] for f in FLOWS}
tier1 = [s for s in SLICES if s['tier'].startswith('1')]

# ------------------------------------------------------------------ 05 overview
O = [GENERATED, '', '[Implementation plan](../README.md) / Vertical slices', '', '# Vertical Slices', '',
     'The system is released as thin end-to-end slices that cross domains, not domain by domain. Each slice delivers one workflow a user can perform from start to finish, '
     'takes from every domain only the requirements that workflow needs, and is closed by a gate. The slices follow the four critical flows of the '
     'Domain Scope document (section 5) and are placed in the phases of the PRS delivery sequence (section 16.1).', '',
     f'There are {len(SLICES)} slices covering all {len(FR)} functional requirements of the ten [domain specifications](../../domain_specs/README.md); each requirement belongs to exactly one slice.', '',
     'Order is expressed as "after": a slice passes its gate only after the slices it comes after have passed theirs. Its sessions start earlier, on the contracts of those slices (see the [session plan](sessions.md#shape)). Slices with no path between them can be built in parallel. No durations are implied.', '',
     '<a id="done"></a>', '', '## 1. What "done" means for a slice', '',
     'A slice is done when its workflow passes end to end, in an integrated environment, across every domain it touches. This is the rule of PRS acceptance gate ACC-002 '
     '("All Tier 1 workflows SHALL pass end-to-end clinical scenario tests with clinical owner approval"), applied to every slice. Specifically:', '',
     '1. **Scenario.** The end-to-end scenario written for the slice runs from first step to last with no manual repair between domains, including its failure branches.',
     '2. **Workflows.** Every specification workflow listed as a gate for the slice passes its end-to-end test.',
     '3. **Requirements.** Every Must requirement in the slice passes its acceptance criteria, and its test scenarios in section 15.2 of the owning specification pass (ACC-001).',
     '4. **Owner approval.** The clinical owner signs the scenario for a Tier 1 slice (ACC-002); the business owner signs for other slices.',
     '5. **Interfaces.** Each interface the slice introduces shows acknowledgement, error handling, replay, reconciliation and monitoring (ACC-005).',
     '6. **Downtime.** A Tier 1 slice has rehearsed its downtime procedure and restoration reconciliation (ACC-007).',
     '7. **No regression.** The scenarios of every slice it comes after still pass.', '',
     'A requirement that is built but whose slice scenario has not passed is not done. Should and Could requirements in a slice may be deferred with the owner\'s agreement without holding the gate; the deferral is recorded against the slice.', '',
     '## 2. Slice map', '',
     'Rows are PRS phases; columns are flows. A slice appears in the phase in which it is released.', '',
     '| PRS phase | ' + ' | '.join(f'{f[1]}' for f in FLOWS) + ' |', '|---|' + '---|' * len(FLOWS)]
for ph, pn in PHASES.items():
    O.append(f'| **{ph}. {pn}** | ' + ' | '.join('<br>'.join(f'{SL(s["id"], 1)} {s["title"]}' for s in SLICES if s['phase'] == ph and s['flow'] == f[0]) or '–' for f in FLOWS) + ' |')
O += ['', 'Phase 0 (mobilise and discover) and phase 7 (scale and continuous improvement) release no slice. Phase 0 must settle the decisions listed against the earliest slices; phase 7 repeats the passed slices at further facilities.', '',
      '## 3. Slice sequence', '', '```mermaid', 'flowchart LR']
for ph, pn in PHASES.items():
    O.append(f'  subgraph P{ph}["Phase {ph}: {pn}"]')
    O += [f'    {s["id"].replace("-", "")}["{s["id"]}"]' for s in SLICES if s['phase'] == ph]
    O.append('  end')
for s in SLICES:
    O += [f'  {a.replace("-", "")} --> {s["id"].replace("-", "")}' for a in s['after']]
O += ['```', '', 'An arrow points from a slice to one that comes after it.', '',
      '| Slice | Title | Phase | Tier | After | Domains | Requirements (Must / Should / Could) | Workflows gating it | Decisions to settle |', '|---|---|---|---|---|---|---|---|---|']
for s in SLICES:
    O.append(f'| {SL(s["id"], 1)} | {s["title"]} | {s["phase"]} | {s["tier"]} | {", ".join(SL(a, 1) for a in s["after"]) or "–"} | {", ".join(s["doms"])} | '
             f'{len(s["frs"])} ({s["prio"]["Must"]} / {s["prio"]["Should"]} / {s["prio"]["Could"]}) | {len(s["wfs"])} | {len(s["decs"])} |')
O += ['', '## 4. The flows', '', '| Flow | Source | What it delivers | Slices | Requirements | Detail |', '|---|---|---|---|---|---|']
for code, name, src, desc in FLOWS:
    ss = [s for s in SLICES if s['flow'] == code]
    O.append(f'| {name} | {src} | {desc} | {len(ss)} | {sum(len(s["frs"]) for s in ss)} | [slices/{code}.md](slices/{code}.md) |')
O += ['', '## 5. What can run in parallel', '',
      'Slices with no "after" path between them are independent. After each slice below passes its gate, the listed slices can pass theirs (subject to their other predecessors); their sessions start earlier, once its contracts are fixed.', '',
      '| When this passes | These can start |', '|---|---|']
for s in SLICES:
    nxt = [x['id'] for x in SLICES if s['id'] in x['after']]
    if nxt:
        O.append(f'| {SL(s["id"], 1)} | {", ".join(SL(n, 1) for n in nxt)} |')
depth = {}


def _depth(sid):
    if sid not in depth:
        depth[sid] = 1 + max((_depth(a) for a in BY[sid]['after']), default=0)
    return depth[sid]


for s in SLICES:
    _depth(s['id'])
longest = max(depth.values())
chain = [max(depth, key=depth.get)]
while BY[chain[0]]['after']:
    chain.insert(0, max(BY[chain[0]]['after'], key=lambda a: depth[a]))
O += ['', f'The longest chain of slices that must follow one another is {longest} long: ' + ' → '.join(SL(c, 1) for c in chain) + '. '
      'Everything else can be arranged around that chain as team capacity allows.', '',
      '## 6. Alignment with the PRS delivery sequence', '',
      'Every slice is released in the phase of PRS section 16.1 (as amended 15 November 2026) that lists its scope. The earlier conflicts between phases are recorded in [phase alignment](phase-alignment.md). Three slices need a note:', '',
      '| Slice | PRS position | Position here |', '|---|---|---|']
O += [f'| {SL(a, 1)} | {b} | {c} |' for a, b, c in PHASE_NOTES]
O += ['', 'Several phase 5 slices have only early predecessors and could start well before phase 5 if capacity allows: ' +
      ', '.join(f'{SL(s["id"], 1)} (after {", ".join(s["after"])})' for s in SLICES if s['phase'] == 5 and all(BY[a]['phase'] <= 2 for a in s['after'])) + '.', '',
      '## 7. Checks on this slicing', '',
      f'- **Coverage.** All {len(FR)} functional requirements are assigned to exactly one slice; the build script fails otherwise.',
      f'- **Order.** No slice comes after a slice released in a later phase.',
      f'- **Workflows.** {len(WF) - len(unplaced_wf)} of the {len(WF)} specification workflows gate a slice. A workflow gates the slice that holds most of the requirements citing it, except where slices_def.py places it by hand (gate_wfs).'
      + (f' Not cited by any requirement, so not placed: {", ".join(L(w, 1) for w in unplaced_wf)}.' if unplaced_wf else ''),
      f'- **Tests.** {len(TESTS) - untraced_tests} of the {len(TESTS)} test scenarios in the specifications trace to a functional requirement and are counted against its slice; '
      f'{untraced_tests} test non-functional or cross-cutting requirements and apply to every slice.',
      f'- **Tier 1.** {len(tier1)} slices deliver Tier 1 workflows and need clinical owner approval under ACC-002: {", ".join(SL(s["id"], 1) for s in tier1)}.']
ngap = sum(len(s['gaps']) for s in SLICES)
O += [f'- **Module dependencies met by contract, not by order.** In {ngap} cases a requirement names an upstream module of its own domain that has no requirement in the same or an earlier slice. '
      'These are listed in each slice; the slice must build against an agreed contract or stub of that module, or the module must be pulled forward.', '',
      '## 8. Limits', '',
      '- **The assignment is a design judgement.** Which requirement belongs to which slice was decided by reading the requirement titles and the flows, and is recorded in [tools/definitions/slices_def.py](../tools/definitions/slices_def.py). Reviewed 2026-11-24 on the owners\' behalf, under delegated authority: the upstream modules each slice builds against by contract were checked, and BC-2 now comes after BC-1 (payer coverage) and BC-6 (stock ledger), which it needs. The remaining cases are a later module read by an earlier one and stay as contract and stub.',
      '- **Enabling requirements.** Platform and shared-service requirements (Domains 2 and 10) are placed in the first slice whose gate cannot pass without them, so the earliest slices are the widest.',
      '- **Non-functional requirements** (section 10 of each specification) are not sliced; they apply to every slice that touches the domain.',
      '- **Slice size is uneven** and is not an effort measure.',
      '', 'Data: [data/slices.csv](../data/slices.csv). To change the slicing, edit [tools/definitions/slices_def.py](../tools/definitions/slices_def.py) and run [tools/build.py](../tools/build.py).']
write('delivery/slices.md', O)

# ------------------------------------------------------------------ per-flow detail
for code, name, src, desc in FLOWS:
    ss = [s for s in SLICES if s['flow'] == code]
    P = [GENERATED, '', f'[Implementation plan](../../README.md) / [Vertical slices](../slices.md) / {name}', '',
         f'# Flow {code}: {name}', '', f'Source: {src}. {desc}', '',
         f'The rule for "done" is in [section 1 of the slice plan](../slices.md#done).', '',
         '| Slice | Title | Phase | After | Requirements |', '|---|---|---|---|---|']
    P += [f'| [{s["id"]}](#{s["id"].lower()}) | {s["title"]} | {s["phase"]} | {", ".join(SL(a, 2) for a in s["after"]) or "–"} | {len(s["frs"])} |' for s in ss]
    for s in ss:
        P += ['', f'<a id="{s["id"].lower()}"></a>', '', f'## {s["id"]} {s["title"]}', '',
              '| Attribute | Value |', '|---|---|',
              f'| Phase | {s["phase"]}. {PHASES[s["phase"]]} |', f'| Service tier of the workflow | {s["tier"]} |',
              f'| After | {", ".join(SL(a, 2) + " " + BY[a]["title"] for a in s["after"]) or "None; this slice can start first"} |',
              f'| Enables | {", ".join(SL(x["id"], 2) for x in SLICES if s["id"] in x["after"]) or "–"} |',
              f'| Domains | {", ".join(f"D{NUM[a]} {a}" for a in s["doms"])} |',
              f'| Requirements | {len(s["frs"])}: {s["prio"]["Must"]} Must, {s["prio"]["Should"]} Should, {s["prio"]["Could"]} Could |', '',
              f'**Outcome.** {s["outcome"]}', '', '**End-to-end scenario**', '']
        P += [f'{k}. {st}' for k, st in enumerate(s['steps'], 1)]
        P += ['', '**Done when**', '', '- The scenario above passes end to end in an integrated environment, with owner approval'
              + (' by the clinical owner (ACC-002, Tier 1).' if s['tier'].startswith('1') else '.')]
        if s['wfs']:
            P.append('- These specification workflows pass end to end: ' + '; '.join(f'{L(w, 2)} {WF[w]}' for w in sorted(s['wfs'])) + '.')
        if s['tests']:
            P.append(f'- The {sum(s["tests"].values())} test scenarios tracing to this slice\'s requirements pass: '
                     + ', '.join(f'{n} in [{FOLDER[a]} section 15.2]({spec(2, a, "15-testing.md", "s15-2")})' for a, n in sorted(s['tests'].items(), key=lambda x: NUM[x[0]])) + '.')
        P.append('- Every Must requirement below meets its acceptance criteria, and the scenarios of the slices this one comes after still pass.')
        if s['tier'].startswith('1'):
            P.append('- The downtime procedure and restoration reconciliation for this workflow have been rehearsed (ACC-007).')
        P += ['', '**Requirements**', '', '| Domain | Module | Requirement | Title | Priority |', '|---|---|---|---|---|']
        for f in sorted(s['frs'], key=lambda f: (NUM[FR[f]['ab']], FR[f]['mod'], f)):
            r = FR[f]
            P.append(f'| D{NUM[r["ab"]]} {r["ab"]} | {L(r["mod"], 2)} | {L(f, 2)} | {td(r["title"])} | {r["priority"]} |')
        if s['decs']:
            P += ['', '**Decisions to settle before this slice.** Open decisions cited by its Must requirements (see [blocking decisions](../../decisions/blocking-decisions.md)):', '']
            P += [f'- {L(d, 2)}: {DEC[d]["decision_required"]}' for d in s['decs']]
        if s['gaps']:
            P += ['', '**Upstream modules not yet delivered.** These requirements name a module of their own domain that has no requirement in this slice or an earlier one. Build against an agreed contract or stub, or pull the module forward:', '']
            P += [f'- {L(m, 2)} {MODNAME[m]} (first delivered in {", ".join(sorted({assigned[x] for x in MODFRS[m]}, key=ORDER.index)[:1])}): needed by {", ".join(L(f, 2) for f in fs)}.' for m, fs in sorted(s['gaps'].items())]
    write(f'delivery/slices/{code}.md', P)

with open(os.path.join(PLAN, 'data', 'slices.csv'), 'w', newline='') as fh:
    w = csv.writer(fh)
    w.writerow(['slice', 'flow', 'phase', 'tier', 'after', 'requirement_id', 'domain', 'module_id', 'priority', 'title'])
    for s in SLICES:
        for f in s['frs']:
            w.writerow([s['id'], FLOWNAME[s['flow']], s['phase'], s['tier'], ' '.join(s['after']), f, FR[f]['ab'], FR[f]['mod'], FR[f]['priority'], FR[f]['title']])

print('slices', len(SLICES), 'requirements', len(assigned), 'workflows placed', len(WF) - len(unplaced_wf), 'of', len(WF),
      'tests traced', len(TESTS) - untraced_tests, 'of', len(TESTS), 'module-order gaps', ngap, 'longest chain', longest)
for s in SLICES:
    print(f'  {s["id"]:5} P{s["phase"]} reqs={len(s["frs"]):2} wfs={len(s["wfs"])} decs={len(s["decs"]):2} gaps={len(s["gaps"])}')
