#!/usr/bin/env python3
"""Build the stage and slice gates from the slice plan, the domain specifications and the PRS.

Writes  delivery/stage-gates.md and delivery/gates/<FLOW>.md   (under docs/implementation_plan)
Run:    python3 docs/implementation_plan/tools/build_gates.py
It imports build_slices.py, which rebuilds the slice pages first, so the gates always match the slices.

Sources: test scenarios (section 15.2) and operational readiness (section 16.4) of each domain specification;
PRS section 16.1 (phase exit criteria) and section 17.2 (acceptance gates ACC-001 to ACC-010).
The mapping of ACC gates to stages (ACC_AT_STAGE) and of clinical-content slices (ACC010_SLICES) is hand-authored below.
"""
import re, os, sys, csv, collections

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, 'definitions'))
sys.dont_write_bytecode = True
import build_slices as bs  # noqa: E402  (runs the slice build)

PLAN, SPECS, ABBR, FOLDER, NUM = bs.PLAN, bs.SPECS, bs.ABBR, bs.FOLDER, bs.NUM
SLICES, BY, FR, WF, PHASES, FLOWS, assigned = bs.SLICES, bs.BY, bs.FR, bs.WF, bs.PHASES, bs.FLOWS, bs.assigned
plain, td, spec, L = bs.plain, bs.td, bs.spec, bs.L
GENERATED = '<!-- Generated by tools/build_gates.py from the slice plan, docs/domain_specs and the PRS. Do not edit by hand; re-run the script. -->'
PRS_REL = '../../initial_requirements/Enterprise_Hospital_Information_System_Product_Requirements_Specification_v3.0.md'

# ---------------------------------------------------------------- hand-authored mappings
# What each PRS acceptance gate requires at each stage. A gate not listed for a stage has nothing new to show there.
ACC_AT_STAGE = {
    'ACC-001': {s: 'Every Must requirement in the slices of this stage passes verification or has an approved, time-bound waiver; the traceability matrix is signed for the stage.' for s in range(1, 7)},
    'ACC-002': {},  # filled from Tier 1 slices
    'ACC-003': {s: 'No unresolved critical or high vulnerability in anything released in this stage without formal risk acceptance.' for s in range(1, 7)},
    'ACC-004': {1: 'Duplicate, twin and changed-demographics matching scenarios pass on representative data; no unsafe automatic merge (slice RC-1).',
                2: 'Merge and unmerge, newborn and unknown-patient scenarios pass, with steward workflow evidence (slices RC-3 and RC-4). The gate is complete at this stage.'},
    'ACC-005': {2: 'ADT and demographics exchange shows acknowledgement, error handling, replay, reconciliation and monitoring.',
                3: 'The order and result contract with Domain 4 passes contract tests against the simulator.',
                4: 'Laboratory, analyzer, imaging and modality, blood bank, device and dispensing-cabinet interfaces each pass conformance and outage tests.',
                5: 'Payer eligibility and claims, finance posting, patient-facing and third-party application interfaces, and analytical feeds each pass conformance and outage tests.',
                6: 'Feeds added for outcome evaluation and any AI gateway pass the same tests.'},
    'ACC-006': {2: 'Backup restore and disaster recovery meet the approved RTO and RPO for the services released so far (first demonstrated in slice RC-3).',
                3: 'Repeated for the clinical record and ordering services at their approved tier.',
                4: 'Repeated for ancillary, medication and stock services.',
                5: 'Repeated for revenue, record-management, portal and data-platform services.',
                6: 'Repeated for services added in this stage.'},
    'ACC-007': {},  # filled from Tier 1 slices
    'ACC-008': {3: 'Complete export of data and configuration is demonstrated and independently validated for everything released so far (slice XF-1).',
                4: 'Export repeated to include ancillary, medication and stock data.',
                5: 'Export repeated to include financial, record-management and portal data.',
                6: 'Export repeated to include analytical products and pathway evaluation data.'},
    'ACC-009': {s: 'Support team, super-users, runbooks, escalation paths and service dashboards are operational for the domains released in this stage (see the readiness items below).' for s in range(1, 7)},
    'ACC-010': {3: 'Clinical governance approves the documentation templates, order catalogue and order sets, decision-support rules and alerts, and the terminology bindings used at this stage; the first pathway content is approved before publication.',
                4: 'Clinical governance approves medication rules, formulary content, critical-result rules, perioperative checklists and the pathways to be activated.',
                6: 'Clinical governance approves outcome measure definitions and any advanced decision-support content.'},
}
ACC010_SLICES = {'RC-5', 'OR-1', 'OR-3', 'OR-6', 'OR-7', 'PA-1', 'PA-2', 'PA-3', 'PA-4'}
ACC004_SLICES = {'RC-1', 'RC-3', 'RC-4'}
ACC_PRIMARY = {'ACC-001': 2, 'ACC-002': 3, 'ACC-003': 2, 'ACC-004': 1, 'ACC-005': 2, 'ACC-006': 2, 'ACC-007': 2, 'ACC-008': 2, 'ACC-009': 2, 'ACC-010': 3}

# ---------------------------------------------------------------- load
prs = open(os.path.join(PLAN, 'delivery', PRS_REL)).read()
ACC = {}
for m in re.finditer(r'^\| (ACC-\d{3}) \| (.*?) \| ([MSC]) \| (.*?) \|$', prs, re.M):
    ACC[m.group(1)] = dict(req=m.group(2), evidence=m.group(4))
assert len(ACC) == 10, len(ACC)
PHASE_EXIT, PHASE_SCOPE = {}, {}
sec = prs[prs.index('### 16.1 Recommended delivery sequence'):prs.index('### 16.2')]
for m in re.finditer(r'^\| (\d)\. [^|]* \| (.*?) \| (.*?) \|$', sec, re.M):
    PHASE_SCOPE[int(m.group(1))], PHASE_EXIT[int(m.group(1))] = m.group(2), m.group(3)

TESTS, READY, ACCEPT = [], {}, {}
for ab in ABBR:
    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('|')]
        frs = re.findall(r'FR-[A-Z]{3}-[A-Z]{2,4}-\d{3}', c[1])
        TESTS.append(dict(id=c[0], ab=ab, req=c[1], frs=frs, scenario=c[2], type=c[3], expected=c[4] if len(c) > 4 else ''))
    t = open(os.path.join(SPECS, FOLDER[ab], '16-implementation.md')).read()
    s164 = t[t.index('<a id="s16-4"></a>'):]
    rows = [[plain(x).strip() for x in r.strip().strip('|').split('|')] for r in re.findall(r'^\| [^\n]*$', s164, re.M)[1:]]  # [0] is the header; the |---| row does not match
    READY[ab] = [r for r in rows if len(r) >= 3]

for s in SLICES:
    s['gate_tests'] = []
cross = collections.defaultdict(list)
for t in TESTS:
    sl = [assigned[f] for f in t['frs'] if f in assigned]
    if sl:
        BY[sl[0]]['gate_tests'].append(t)
    else:
        cross[t['ab']].append(t)

IFS = collections.defaultdict(set)
for r in csv.DictReader(open(os.path.join(PLAN, 'data', 'backlog.csv'))):
    for i in r['interfaces_events'].split():
        if i.startswith('IF-'):
            IFS[assigned[r['requirement_id']]].add(i)

first_stage = {}
for s in sorted(SLICES, key=lambda s: s['phase']):
    for ab in s['doms']:
        first_stage.setdefault(ab, s['phase'])
for s in SLICES:
    t1 = s['tier'].startswith('1')
    s['acc'] = ['ACC-001'] + (['ACC-002'] if t1 else []) + (['ACC-004'] if s['id'] in ACC004_SLICES else []) + \
        (['ACC-005'] if IFS[s['id']] else []) + (['ACC-007'] if t1 else []) + (['ACC-008'] if s['id'] == 'XF-1' else []) + \
        (['ACC-010'] if s['id'] in ACC010_SLICES else [])
for ph in PHASES:
    t1 = [s['id'] for s in SLICES if s['phase'] == ph and s['tier'].startswith('1')]
    if t1:
        ACC_AT_STAGE['ACC-002'][ph] = f'The end-to-end clinical scenarios of the Tier 1 slices of this stage pass with clinical owner approval: {", ".join(t1)}.'
        ACC_AT_STAGE['ACC-007'][ph] = f'Downtime procedure and restoration reconciliation are rehearsed by the departments that use: {", ".join(t1)}.'


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


def GL(sid):
    return f'[gate](gates/{BY[sid]["flow"]}.md#{sid.lower()})'


def TL(t, depth):
    return f'[{t["id"]}]({spec(depth, t["ab"], "15-testing.md", t["id"].lower())})'


def dom(ab, depth=1):
    return f'[D{NUM[ab]} {ab}]({spec(depth, ab, "README.md")})'


# ---------------------------------------------------------------- 06 overview
nt = sum(len(s['gate_tests']) for s in SLICES)
O = [GENERATED, '', '[Implementation plan](../README.md) / Stage gates', '', '# Stage Gates', '',
     'Exit criteria for every slice and every stage of the delivery sequence. A slice or stage is finished when its gate is passed with evidence, not when its work is built. '
     'The criteria are taken from three sources: the test scenarios in section 15.2 of each domain specification, the operational readiness items in section 16.4, '
     f'and the acceptance gates ACC-001 to ACC-010 of [PRS section 17.2]({PRS_REL}).', '',
     '## 1. The three levels of gate', '',
     '| Level | Closes | Passed when | Signed by |', '|---|---|---|---|',
     '| Slice gate | One [vertical slice](slices.md) | Its end-to-end scenario, its specification workflows and its test scenarios pass, and the ACC gates that apply to it are shown for its scope | Clinical owner for a Tier 1 slice (ACC-002); business owner otherwise |',
     '| Stage gate | One phase of PRS section 16.1 | Every slice gate of the stage is passed, the PRS exit criteria of the phase are met, each ACC gate is shown for the stage, and the readiness items of every domain released in the stage have evidence | Product governance, with clinical governance for stages that release clinical workflows |',
     '| Go-live gate | A production release to a facility | The stage gate is passed and ACC-001 to ACC-010 are all satisfied for the release scope, with no open waiver past its date | As PRS section 17.2 and the hospital\'s go-live authority |', '',
     'A stage gate is not a go-live decision. Stages 1 and 2 can pass their gates without any production use; the first stage that can carry clinical go-live is stage 3.', '',
     '**Evidence.** PRS section 17.3 applies to every gate: evidence is kept in a controlled repository with test case ID, requirement ID, build and version, environment, test data classification, tester, date, outcome, defect references, approver and any waiver. '
     'Clinical test evidence uses approved synthetic or de-identified data unless production validation is explicitly authorized.', '',
     '**Waivers.** A Must requirement or test may be waived only with an approved, time-bound waiver (ACC-001). A waiver does not pass a Tier 1 scenario (ACC-002) or accept a critical or high vulnerability without leadership risk acceptance (ACC-003).', '',
     '<a id="acc"></a>', '', '## 2. PRS acceptance gates and where they apply', '',
     '| Gate | Requirement | Evidence required by the PRS | Checked at slice gates | Checked at stage gates | Primary domain |', '|---|---|---|---|---|---|']
for a, v in ACC.items():
    sl = [s['id'] for s in SLICES if a in s['acc']]
    slt = 'Every slice' if len(sl) == len(SLICES) else (', '.join(SL(x) for x in sl) or '–')
    st = sorted(ACC_AT_STAGE[a])
    O.append(f'| {a} | {td(v["req"])} | {td(v["evidence"])} | {slt} | {", ".join(str(x) for x in st)} | {dom(ABBR[ACC_PRIMARY[a] - 1])} |')
O += ['', 'ACC-005 is checked at the gate of every slice whose requirements name an interface; ACC-003, ACC-006 and ACC-009 are shown per stage, because they concern the released system as a whole and not one workflow.', '',
      '## 3. Stage gates', '']
for ph, pn in PHASES.items():
    ss = [s for s in SLICES if s['phase'] == ph]
    must = sum(s['prio']['Must'] for s in ss)
    newdom = [ab for ab in ABBR if first_stage.get(ab) == ph]
    O += [f'<a id="stage-{ph}"></a>', '', f'### Stage {ph}: {pn}', '',
          f'**Scope (PRS 16.1).** {PHASE_SCOPE[ph]}', '',
          f'**Exit criteria (PRS 16.1).** {PHASE_EXIT[ph]}', '',
          f'**Size of the gate.** {len(ss)} slices, {sum(len(s["frs"]) for s in ss)} requirements ({must} Must), {sum(len(s["gate_tests"]) for s in ss)} test scenarios, '
          f'{sum(len(s["wfs"]) for s in ss)} specification workflows.', '',
          '**1. Slice gates.** All of these are passed:', '',
          '| Slice | Title | Tier | Signed by | Workflows | Tests | ACC gates at the slice | Detail |', '|---|---|---|---|---|---|---|---|']
    for s in ss:
        O.append(f'| {SL(s["id"])} | {s["title"]} | {s["tier"]} | {"Clinical owner" if s["tier"].startswith("1") else "Business owner"} | {len(s["wfs"])} | {len(s["gate_tests"])} | {", ".join(s["acc"])} | {GL(s["id"])} |')
    O += ['', '**2. PRS acceptance gates shown for this stage.**', '', '| Gate | What must be shown at this stage | Evidence |', '|---|---|---|']
    for a in ACC:
        if ph in ACC_AT_STAGE[a]:
            O.append(f'| {a} | {ACC_AT_STAGE[a][ph]} | {td(ACC[a]["evidence"])} |')
    O += ['', '**3. Operational readiness.** ' + (
        f'Domains first released in this stage: {", ".join(dom(ab) for ab in newdom)}. Every item below has its evidence before the stage gate passes (ACC-009). '
        'Domains released in an earlier stage extend their evidence to the modules added in this stage.' if newdom else
        'No domain is first released in this stage. Each domain touched extends its readiness evidence from earlier stages to the modules added here: '
        + ', '.join(dom(ab) for ab in sorted({a for s in ss for a in s['doms']}, key=lambda a: NUM[a])) + '.'), '']
    if newdom:
        O += ['| Domain | Readiness item | Required evidence | Responsible owner |', '|---|---|---|---|']
        for ab in newdom:
            for r in READY[ab]:
                O.append(f'| [D{NUM[ab]} {ab}]({spec(1, ab, "16-implementation.md", "s16-4")}) | {td(r[0])} | {td(r[1])} | {td(r[2])} |')
        O.append('')
    xs = [ab for ab in ABBR if first_stage.get(ab, 99) <= ph and cross[ab] and ab in {a for s in ss for a in s['doms']}]
    O += ['**4. Cross-cutting tests.** ' + (
        'The non-functional and cross-cutting test scenarios of the domains touched in this stage pass for the released scope: '
        + ', '.join(f'{len(cross[ab])} in [{FOLDER[ab]} section 15.2]({spec(1, ab, "15-testing.md", "s15-2")})' for ab in xs) + '. '
        if xs else 'None beyond the slice tests. ') +
        'Each domain\'s own acceptance conditions in section 15.3 of its specification are met for the modules released.', '',
        '**5. No regression.** The scenarios of every slice passed in earlier stages still pass on the build that is put forward for this gate.', '']
O += ['## 4. Slice gate index', '',
      f'Each slice gate lists its criteria and the {nt} test scenarios that trace to its requirements. The detail is in one page per flow.', '',
      '| Flow | Slices | Test scenarios | Gate detail |', '|---|---|---|---|']
for code, name, src, desc in FLOWS:
    ss = [s for s in SLICES if s['flow'] == code]
    O.append(f'| {name} | {", ".join(s["id"] for s in ss)} | {sum(len(s["gate_tests"]) for s in ss)} | [gates/{code}.md](gates/{code}.md) |')
O += ['', '## 5. Tests that belong to no slice', '',
      f'{sum(len(v) for v in cross.values())} test scenarios in the specifications verify non-functional or cross-cutting requirements and trace to no functional requirement. '
      'They are applied at the stage gate of every stage that releases part of the domain (item 4 of each stage gate).', '',
      '| Domain | Tests | First applied at stage | Test scenarios |', '|---|---|---|---|']
for ab in ABBR:
    if cross[ab]:
        O.append(f'| {dom(ab)} | {len(cross[ab])} | {first_stage[ab]} | {", ".join(TL(t, 1) for t in cross[ab])} |')
O += ['', '## 6. Limits', '',
      '- **Stage mapping of ACC gates is a judgement.** What each ACC gate must show at each stage is written by hand in [tools/build_gates.py](../tools/build_gates.py) and should be reviewed by the gate owners.',
      '- **Test placement follows requirements.** A test is counted at the slice of the first functional requirement it cites. A test that spans several slices is run again wherever its other requirements are released.',
      '- **Readiness items are due when a domain is first released.** Items that only make sense for later modules (for example downtime forms for a workflow released later) are extended at that later stage.',
      '- **Numeric targets are not set here.** Where a readiness item or test refers to an approved target (RTO, RPO, response time), the target is the one approved for the service tier; several are still open decisions in the specifications.',
      '- **Status is not tracked in this file.** It defines the gates; recording that a gate has passed belongs in the evidence repository.']
bs.write('delivery/stage-gates.md', O)

# ---------------------------------------------------------------- per-flow gate 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) / [Stage gates](../stage-gates.md) / {name}', '',
         f'# Slice Gates: {name}', '',
         f'Gate criteria and test scenarios for the slices of this flow. Slice content is in [slices/{code}.md](../slices/{code}.md); stage gates and the rules for evidence and waivers are in [stage-gates.md](../stage-gates.md).', '',
         '| Slice | Title | Stage | Tests |', '|---|---|---|---|']
    P += [f'| [{s["id"]}](#{s["id"].lower()}) | {s["title"]} | {s["phase"]} | {len(s["gate_tests"])} |' for s in ss]
    for s in ss:
        t1 = s['tier'].startswith('1')
        P += ['', f'<a id="{s["id"].lower()}"></a>', '', f'## {s["id"]} {s["title"]}', '',
              f'Stage {s["phase"]} ({PHASES[s["phase"]]}). Tier: {s["tier"]}. Slice definition: {SL(s["id"], 2)}. '
              f'Comes after: {", ".join(SL(a, 2) for a in s["after"]) or "none"}.', '',
              '**Gate criteria**', '',
              '| No. | Criterion | Evidence | Source |', '|---|---|---|---|',
              f'| 1 | The end-to-end scenario of the slice passes in an integrated environment with no manual repair between domains | Signed scenario run by the {"clinical" if t1 else "business"} owner | {"ACC-002" if t1 else "Slice definition"} |']
        n = 2
        if s['wfs']:
            P.append(f'| {n} | These specification workflows pass end to end: ' + '; '.join(f'{L(w, 2)} {WF[w]}' for w in sorted(s['wfs'])) + ' | Workflow test results | Section 4.2 of the specifications |')
            n += 1
        P.append(f'| {n} | All {len(s["gate_tests"])} test scenarios below pass | Test results per PRS 17.3 | Section 15.2 of the specifications |')
        n += 1
        P.append(f'| {n} | Every Must requirement of the slice ({s["prio"]["Must"]}) meets its acceptance criteria or has an approved, time-bound waiver | Signed traceability matrix for the slice | ACC-001 |')
        n += 1
        if 'ACC-004' in s['acc']:
            P.append(f'| {n} | The identity safety scenarios in this slice\'s scope pass (duplicate, twin, newborn, unknown patient, merge and unmerge as applicable) | Identity test report and steward workflow evidence | ACC-004 |')
            n += 1
        if 'ACC-005' in s['acc']:
            P.append(f'| {n} | Each interface the slice uses shows acknowledgement, error handling, replay, reconciliation and monitoring: {", ".join(sorted(IFS[s["id"]]))} | Interface conformance and outage test results | ACC-005 |')
            n += 1
        if t1:
            P.append(f'| {n} | The downtime procedure and restoration reconciliation for this workflow are rehearsed by the departments that use it | Exercise report and corrective action closure | ACC-007 |')
            n += 1
        if 'ACC-008' in s['acc']:
            P.append(f'| {n} | A complete export of data and configuration in documented formats is produced and independently validated | Independent export validation | ACC-008 |')
            n += 1
        if 'ACC-010' in s['acc']:
            P.append(f'| {n} | Clinical governance has approved the clinical content the slice uses (templates, order sets, rules, alerts, terminology or pathway content as applicable) | Approved clinical content catalogue | ACC-010 |')
            n += 1
        for crit, ev, src in s.get('gate_extra', []):
            P.append(f'| {n} | {crit} | {ev} | {src} |')
            n += 1
        P.append(f'| {n} | The scenarios of the slices this one comes after still pass on the same build | Regression run | Slice sequence |')
        if s['decs']:
            P += ['', f'Open decisions cited by this slice\'s Must requirements are listed in the [slice definition](../slices/{code}.md#{s["id"].lower()}); a criterion that depends on an undecided value cannot be signed until the value is approved.']
        P += ['', '**Test scenarios**', '']
        if s['gate_tests']:
            P += ['| Test | Requirement | Scenario | Type | Expected result |', '|---|---|---|---|---|']
            for t in sorted(s['gate_tests'], key=lambda t: (NUM[t['ab']], t['id'])):
                P.append(f'| {TL(t, 2)} | {", ".join(L(f, 2) for f in t["frs"])} | {td(t["scenario"])} | {td(t["type"])} | {td(t["expected"])} |')
        else:
            P.append('The specifications define no test scenario that traces to this slice\'s requirements. The slice scenario and workflows are its tests; scenarios should be added to section 15.2 of the owning specification.')
    bs.write(f'delivery/gates/{code}.md', P)

none = [s['id'] for s in SLICES if not s['gate_tests']]
print('gates: stages', len(PHASES), 'slices', len(SLICES), 'tests placed', nt, 'cross-cutting', sum(len(v) for v in cross.values()),
      'slices without tests', none, 'first stage per domain', first_stage)
