#!/usr/bin/env python3
"""Extract implementation-planning inputs from the domain specifications.

Reads   docs/domain_specs/D??-???/...
Writes  delivery/backlog.md, delivery/backlog/D??-???.md, delivery/dependency-graph.md,
        decisions/blocking-decisions.md, data/*.csv   (all under docs/implementation_plan)

Run from anywhere:  python3 docs/implementation_plan/tools/extract.py
Standard library only. Everything written by this script is regenerated on each run;
do not edit those files by hand.
"""
import re, os, glob, csv, collections

HERE = os.path.dirname(os.path.abspath(__file__))
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)}
# Ordering rule: A is placed after B when the weight of "A needs B" exceeds the weight of "B needs A" by at least the margin.
# Below the margin the pair is treated as mutual (no order; agree the contract first).
DOMAIN_MARGIN = 3      # weights are counts of requirements naming the other domain as upstream
MODULE_MARGIN = 2      # weights are requirement mentions (1 each) plus the module overview's own dependency list
OVERVIEW_WEIGHT = 2
GENERATED = '<!-- Generated by tools/extract.py from docs/domain_specs. Do not edit by hand; re-run the script. -->'


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


def domains_in(t):
    out = set()
    for m in re.finditer(r'Domains? ((?:(?:10|[1-9])(?: \([A-Z]{3}\))?(?:, and |, | and | or )?)+)', t):
        out |= {int(x) for x in re.findall(r'\b(10|[1-9])\b', re.sub(r'\([A-Z]{3}\)', '', m.group(1)))}
    return out


def cells(row):
    return [c.strip() for c in row.strip().strip('|').split('|')]


def section(text, start_anchor, end_anchor=None):
    a = text.find(f'<a id="{start_anchor}"></a>')
    if a < 0:
        return ''
    b = text.find(f'<a id="{end_anchor}"></a>', a) if end_anchor else -1
    return text[a:b if b > 0 else len(text)]


def read(*p):
    return open(os.path.join(SPECS, *p)).read()


# ------------------------------------------------------------------ parse
D = {}
for ab in ABBR:
    f = FOLDER[ab]
    title = plain(re.search(r'^# (.*)$', read(f, 'README.md'), re.M).group(1))
    d = dict(ab=ab, folder=f, num=NUM[ab], name=title.split('–', 1)[1].strip(), mods=[], frs=[], decs=[], xd=[],
             ifs=[], migs=[], impl=[])
    for path in sorted(glob.glob(os.path.join(SPECS, f, '05-functional-requirements', 'MOD-*.md'))):
        raw = open(path).read()
        fn = os.path.basename(path)
        h = re.search(r'^## (5\.\d+) Module Specification: (.*)$', raw, re.M)
        mid = re.match(r'(MOD-[A-Z]+-\d{3})', fn).group(1)
        mod = dict(id=mid, file=fn, sec=h.group(1), name=h.group(2).strip(), needs_mod=collections.Counter(),
                   needs_dom=collections.Counter(), frs=[])
        dep = re.search(r'^\*\*Dependencies:\*\*\n((?:- .*\n?)+)', raw, re.M)
        if dep:
            t = plain(dep.group(1))
            for m in set(re.findall(r'MOD-' + ab + r'-\d{3}', t)) - {mid}:
                mod['needs_mod'][m] += OVERVIEW_WEIGHT
            for n in domains_in(t) - {d['num']}:
                mod['needs_dom'][n] += 1
        blocks = re.split(r'^(?=#### Requirement )', raw, flags=re.M)[1:]
        for b in blocks:
            hm = re.match(r'#### Requirement (FR-[A-Z0-9-]+): (.*)', b)
            p = plain(b)

            def attr(name):
                m = re.search(r'^\| ' + name + r' \| (.*?) \|$', p, re.M)
                return m.group(1).strip() if m else ''

            def line(label):
                m = re.search(r'^- ' + label + r'[^:]*:(.*)$', p, re.M)
                return m.group(1).strip() if m else ''
            up, down, req = line('Upstream'), line('Downstream'), line('Required')
            fr = dict(id=hm.group(1), title=hm.group(2).strip(), mod=mid, file=fn,
                      priority=(attr('Priority').split() or [''])[0], priority_note=attr('Priority'),
                      criticality=(attr('Criticality').split() or [''])[0], source=attr('Source'),
                      up_mods=sorted(set(re.findall(r'MOD-' + ab + r'-\d{3}', up)) - {mid}),
                      up_doms=sorted(domains_in(up) - {d['num']}),
                      down_doms=sorted(domains_in(down) - {d['num']}),
                      ifs=sorted(set(re.findall(r'(?:IF|EVT)-' + ab + r'-\d{3}', req))),
                      decs=sorted(set(re.findall(r'DEC-' + ab + r'-\d{3}', p))),
                      gaps=sorted(set(re.findall(r'GAP-' + ab + r'-\d{3}', p))))
            for m in fr['up_mods']:
                mod['needs_mod'][m] += 1
            for n in fr['up_doms']:
                mod['needs_dom'][n] += 1
            mod['frs'].append(fr)
            d['frs'].append(fr)
        d['mods'].append(mod)
    t18 = read(f, '18-assumptions-decisions-gaps.md')
    for row in re.findall(r'^\| <a id="dec-[^\n]*$', t18, re.M):
        c = [plain(x) for x in cells(row)]
        d['decs'].append(dict(id=c[0], decision=c[1], options=c[2], rec=c[3], owner=c[4], status=c[5] if len(c) > 5 else ''))
    d['gap_count'] = len(re.findall(r'^\| <a id="gap-', t18, re.M))
    d['gap_closed'] = len([l for l in re.findall(r'^\| <a id="gap-.*$', t18, re.M) if re.search(r'[Cc]losed', l.rsplit('|', 2)[-2])])
    d['asm_count'] = len(re.findall(r'^\| <a id="asm-', t18, re.M))
    t17 = read(f, '17-traceability.md')
    for row in re.findall(r'^\| <a id="xd-[^\n]*$', t17, re.M):
        c = [plain(x) for x in cells(row)]

        def side(t):
            if re.search(r'\ball\b', t, re.I):
                return set(range(1, 11))
            return domains_in(t)
        d['xd'].append(dict(id=c[0], src=side(c[1]), dst=side(c[2]), src_text=c[1], dst_text=c[2], what=c[3], type=c[4]))
    t08 = read(f, '08-integration.md')
    d['ifs'] = [(m.group(1), m.group(2).strip()) for m in re.finditer(r'^### Interface (IF-[A-Z]+-\d{3}): (.*)$', t08, re.M)]
    d['evt_count'] = len(re.findall(r'^\| <a id="evt-', t08, re.M))
    d['ext'] = [[plain(x) for x in cells(r)] for r in re.findall(r'^\| <a id="ext-[^\n]*$', t08, re.M)]
    d['int_count'] = len(re.findall(r'^\| <a id="int-', t08, re.M))
    d['migs'] = [[plain(x) for x in cells(r)] for r in re.findall(r'^\| <a id="mig-[^\n]*$', read(f, '07-data.md'), re.M)]
    s162 = section(read(f, '16-implementation.md'), 's16-2', 's16-3')
    for row in re.findall(r'^\| [^\n]*$', s162, re.M)[1:]:  # [0] is the header; the |---| row does not match
        c = [plain(x) for x in cells(row)]
        if len(c) >= 4:
            d['impl'].append(c[:4])
    d['test_count'] = len(re.findall(r'^\| <a id="test-', read(f, '15-testing.md'), re.M))
    D[ab] = d

BYNUM = {d['num']: d for d in D.values()}


# ------------------------------------------------------------------ ordering
def layers(nodes, need, margin):
    """need[a][b] = weight with which a needs b. Keep the dominant direction of each pair, then layer.
    Returns (layer index per node, hard edges kept, mutual pairs, edges dropped to break cycles)."""
    hard, mutual = {}, []
    for a in nodes:
        for b, w in need.get(a, {}).items():
            if b not in nodes or b == a or not w:
                continue
            r = need.get(b, {}).get(a, 0)
            if r and (b, a, r, w) not in mutual:
                mutual.append((a, b, w, r))
            if w - r >= margin:
                hard[(a, b)] = w
    dropped, layer, left, n = [], {}, set(nodes), 0
    edges = dict(hard)
    while left:
        ready = [a for a in left if not any((a, b) in edges for b in left)]
        if not ready:
            cyc = min(((a, b) for (a, b) in edges if a in left and b in left), key=lambda e: (edges[e], e))
            dropped.append((cyc[0], cyc[1], edges.pop(cyc)))
            continue
        for a in ready:
            layer[a] = n
        left -= set(ready)
        n += 1
    return layer, edges, mutual, dropped


dom_need = {d['num']: collections.Counter() for d in D.values()}
for d in D.values():
    for fr in d['frs']:
        for n in fr['up_doms']:
            dom_need[d['num']][n] += 1
dom_layer, dom_hard, dom_mutual, dom_dropped = layers(set(range(1, 11)), dom_need, DOMAIN_MARGIN)

for d in D.values():
    ids = {m['id'] for m in d['mods']}
    need = {m['id']: m['needs_mod'] for m in d['mods']}
    d['mod_layer'], d['mod_hard'], d['mod_mutual'], d['mod_dropped'] = layers(ids, need, MODULE_MARGIN)
    for m in d['mods']:
        m['layer'] = d['mod_layer'][m['id']]
        m['hard'] = sorted(b for (a, b) in d['mod_hard'] if a == m['id'])


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


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


def link_id(i, depth, modfile=None):
    ab, t = ab_of(i), i.split('-')[0]
    if t == 'FR':
        return f'[{i}]({spec(depth, ab, "05-functional-requirements/" + modfile, i.lower())})'
    if t == 'MOD':
        fn = next(m['file'] for m in D[ab]['mods'] if m['id'] == i)
        return f'[{i}]({spec(depth, ab, "05-functional-requirements/" + fn)})'
    rel = {'DEC': '18-assumptions-decisions-gaps.md', 'GAP': '18-assumptions-decisions-gaps.md', 'IF': '08-integration.md',
           'EVT': '08-integration.md', 'EXT': '08-integration.md', 'MIG': '07-data.md', 'XD': '17-traceability.md'}[t]
    return f'[{i}]({spec(depth, ab, rel, i.lower())})'


def dom_link(n, depth):
    d = BYNUM[n]
    return f'[D{n} {d["ab"]}]({spec(depth, d["ab"], "README.md")})'


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


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')


def write_csv(rel, header, rows):
    path = os.path.join(PLAN, rel)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w', newline='') as fh:
        w = csv.writer(fh)
        w.writerow(header)
        w.writerows(rows)


NAV = '[Implementation plan](../README.md)'
order_domains = sorted(D.values(), key=lambda d: (dom_layer[d['num']], d['num']))

# ------------------------------------------------------------------ 01 backlog
tot = collections.Counter()
L = [GENERATED, '', NAV + ' / Backlog', '', '# Backlog', '',
     'Every functional requirement in the ten domain specifications, grouped by module, with the enabling work each domain also carries '
     '(interfaces, events, external integrations, data migration). One backlog file per domain holds the detail; this page is the summary.', '',
     'Domains are listed in the derived build order of [the dependency graph](dependency-graph.md#domain-sequence).', '',
     '| Domain | Backlog | Modules | Requirements | Must | Should | Could | Interfaces | Events | External integrations | Migrations | Test scenarios | Open decisions | Known gaps |',
     '|---|---|---|---|---|---|---|---|---|---|---|---|---|---|']
for d in order_domains:
    pc = collections.Counter(fr['priority'] for fr in d['frs'])
    row = [len(d['mods']), len(d['frs']), pc['Must'], pc['Should'], pc['Could'], len(d['ifs']), d['evt_count'], len(d['ext']),
           len(d['migs']), d['test_count'], len(d['decs']), d['gap_count']]
    for k, v in zip('mods frs must should could ifs evt ext mig test dec gap'.split(), row):
        tot[k] += v
    L.append(f'| {dom_link(d["num"], 1)} {d["name"]} | [backlog/{d["folder"]}.md](backlog/{d["folder"]}.md) | ' + ' | '.join(map(str, row)) + ' |')
L.append('| **Total** | | ' + ' | '.join(f'**{tot[k]}**' for k in 'mods frs must should could ifs evt ext mig test dec gap'.split()) + ' |')
L += ['', '## How to read the backlog files', '',
      '- **Epic = module.** Each module of a domain specification is one epic; its functional requirements are the backlog items.',
      '- **Order.** Modules appear in the derived build order within the domain (wave 1 first). Modules in the same wave do not depend on each other and can be built in parallel.',
      '- **Needs.** "Modules" are other modules of the same domain that the requirement names as upstream; "Domains" are the other domains it names as upstream.',
      '- **Open decisions.** Decisions from section 18.3 of the specification that the requirement cites. See [blocking decisions](../decisions/blocking-decisions.md).',
      '- **Priority and criticality** are copied from the requirement; the PRS source is the requirement\'s own Source attribute.',
      '', 'The same data is in [data/backlog.csv](../data/backlog.csv).']
write('delivery/backlog.md', L)

rows = []
for d in order_domains:
    B = [GENERATED, '', f'[Implementation plan](../../README.md) / [Backlog](../backlog.md) / {d["folder"]}', '',
         f'# Backlog: Domain {d["num"]} ({d["ab"]}) – {d["name"]}', '',
         f'Source specification: [{d["folder"]}]({spec(2, d["ab"], "README.md")}). '
         f'Domain wave {dom_layer[d["num"]] + 1} in [the domain sequence](../dependency-graph.md#domain-sequence).', '',
         '## Epics (modules) in build order', '', '| Wave | Module | Name | Requirements | Must | Needs modules first | Needs domains |', '|---|---|---|---|---|---|---|']
    mods = sorted(d['mods'], key=lambda m: (m['layer'], m['id']))
    for m in mods:
        B.append(f'| {m["layer"] + 1} | {link_id(m["id"], 2)} | {td(m["name"])} | {len(m["frs"])} | {sum(1 for f in m["frs"] if f["priority"] == "Must")} | '
                 f'{", ".join(m["hard"]) or "–"} | {", ".join(f"D{n}" for n in sorted(m["needs_dom"])) or "–"} |')
    for m in mods:
        B += ['', f'## {m["id"]} – {m["name"]}', '',
              f'Specification: {link_id(m["id"], 2)} (section {m["sec"]}). Wave {m["layer"] + 1} within the domain.'
              + (f' Build after: {", ".join(link_id(x, 2) for x in m["hard"])}.' if m['hard'] else ''), '',
              '| Requirement | Title | Priority | Criticality | PRS source | Needs modules | Needs domains | Open decisions |', '|---|---|---|---|---|---|---|---|']
        for fr in m['frs']:
            B.append(f'| {link_id(fr["id"], 2, fr["file"])} | {td(fr["title"])} | {fr["priority"]} | {fr["criticality"]} | {td(fr["source"])} | '
                     f'{", ".join(fr["up_mods"]) or "–"} | {", ".join(f"D{n}" for n in fr["up_doms"]) or "–"} | '
                     f'{", ".join(link_id(x, 2) for x in fr["decs"]) or "–"} |')
            rows.append([d['num'], d['ab'], dom_layer[d['num']] + 1, m['id'], m['name'], m['layer'] + 1, fr['id'], fr['title'], fr['priority'],
                         fr['criticality'], fr['source'], ' '.join(fr['up_mods']), ' '.join(f'D{n}' for n in fr['up_doms']),
                         ' '.join(f'D{n}' for n in fr['down_doms']), ' '.join(fr['ifs']), ' '.join(fr['decs']), ' '.join(fr['gaps'])])
    B += ['', '## Enabling work', '', '### Interfaces', '', '| Interface | Name |', '|---|---|']
    B += [f'| {link_id(i, 2)} | {td(n)} |' for i, n in d['ifs']] or ['| – | – |']
    B += ['', f'Events to publish or consume: {d["evt_count"]} (see [section 8.5]({spec(2, d["ab"], "08-integration.md", "s8-5")})). '
          f'Internal integrations: {d["int_count"]} (see [section 8.2]({spec(2, d["ab"], "08-integration.md", "s8-2")})).', '',
          '### External integrations', '', '| Integration | External system | Direction | Purpose | Standard / protocol |', '|---|---|---|---|---|']
    B += [f'| {link_id(c[0], 2)} | ' + ' | '.join(td(x) for x in c[1:5]) + ' |' for c in d['ext']] or ['| – | – | – | – | – |']
    B += ['', '### Data migration', '', '| Migration | Source | Target | Data scope | Validation |', '|---|---|---|---|---|']
    B += [f'| {link_id(c[0], 2)} | ' + ' | '.join(td(x) for x in c[1:5]) + ' |' for c in d['migs']] or ['| – | – | – | – | – |']
    B += ['', '### Implementation dependencies stated by the specification', '',
          f'From [section 16.2]({spec(2, d["ab"], "16-implementation.md", "s16-2")}).', '',
          '| Dependency | Required before | Impact if delayed | Owner |', '|---|---|---|---|']
    B += ['| ' + ' | '.join(td(x) for x in c) + ' |' for c in d['impl']]
    write(f'delivery/backlog/{d["folder"]}.md', B)
write_csv('data/backlog.csv', ['domain_no', 'domain', 'domain_wave', 'module_id', 'module', 'module_wave', 'requirement_id', 'title', 'priority',
                               'criticality', 'prs_source', 'needs_modules', 'needs_domains', 'feeds_domains', 'interfaces_events',
                               'open_decisions', 'known_gaps'], rows)

# ------------------------------------------------------------------ 02 dependency graph
G = [GENERATED, '', NAV + ' / Dependency graph', '', '# Dependency Graph', '',
     'Build-order dependencies extracted from the domain specifications. Three sources are used:', '',
     '- the "Upstream dependencies" line of every functional requirement (part 15) and the "Dependencies" list of every module overview;',
     '- the cross-domain dependency table in section 17.4 of every specification;',
     '- the implementation dependencies in section 16.2, which are reproduced in each [domain backlog](backlog.md).', '',
     'The ordering below is derived mechanically and is an input to sequencing, not the delivery sequence itself. '
     'It shows what cannot start before something else exists and what can run in parallel.', '',
     '<a id="domain-sequence"></a>', '', '## 1. Domain sequence', '',
     'A domain "needs" another when its requirements name that domain as upstream. Domain A is placed after domain B when the number of A\'s requirements needing B '
     f'exceeds the number of B\'s requirements needing A by at least {DOMAIN_MARGIN}. Smaller differences set no order; see [two-way dependencies](#mutual). '
     'Domains in the same wave have no ordering constraint between them and can be built in parallel.', '',
     '| Wave | Domain | Must be preceded by | Requirements naming each upstream domain |', '|---|---|---|---|']
for d in order_domains:
    n = d['num']
    pre = sorted(b for (a, b) in dom_hard if a == n)
    G.append(f'| {dom_layer[n] + 1} | {dom_link(n, 1)} {d["name"]} | {", ".join(f"D{b}" for b in pre) or "–"} | '
             f'{", ".join(f"D{b}: {w}" for b, w in sorted(dom_need[n].items())) or "–"} |')
G += ['', '```mermaid', 'flowchart LR']
for w in sorted(set(dom_layer.values())):
    G.append(f'  subgraph W{w + 1}["Wave {w + 1}"]')
    G += [f'    D{n}["D{n} {BYNUM[n]["ab"]}"]' for n in sorted(dom_layer) if dom_layer[n] == w]
    G.append('  end')
for (a, b), w in sorted(dom_hard.items()):
    if dom_layer[a] - dom_layer[b] == 1 or not any(dom_layer[b] < dom_layer[c] < dom_layer[a] and (a, c) in dom_hard and (c, b) in dom_hard for c in dom_layer):
        G.append(f'  D{b} --> D{a}')
G += ['```', '', 'An arrow points from a domain to one that needs it. Arrows implied by a chain of other arrows are omitted from the diagram; the table above is complete.', '',
      '### Requirement-level need matrix', '', 'Rows need columns. Each cell is the number of functional requirements in the row domain that name the column domain as upstream.', '',
      '| Needs → | ' + ' | '.join(f'D{n} {BYNUM[n]["ab"]}' for n in range(1, 11)) + ' |', '|---|' + '---|' * 10]
for a in range(1, 11):
    G.append(f'| **D{a} {BYNUM[a]["ab"]}** | ' + ' | '.join('·' if a == b else str(dom_need[a].get(b, '')) for b in range(1, 11)) + ' |')
G += ['', '<a id="mutual"></a>', '', '## 2. Two-way dependencies between domains', '',
      'Pairs where each domain names the other as upstream. Ordering alone cannot satisfy both directions: whichever is built first is built against '
      'a contract (API or event) of the other that must be agreed, and stubbed or simulated, beforehand. '
      f'Where the two counts differ by fewer than {DOMAIN_MARGIN}, no order is set and the pair can proceed in parallel on agreed contracts.', '',
      '| Domain A | Domain B | A needs B (requirements) | B needs A (requirements) | Order set |', '|---|---|---|---|---|']
seenp = set()
for a, b, w, r in sorted(dom_mutual, key=lambda x: (-min(x[2], x[3]), -max(x[2], x[3]))):
    if (b, a) in seenp or (a, b) in seenp:
        continue
    seenp.add((a, b))
    order = f'D{a} after D{b}' if (a, b) in dom_hard else (f'D{b} after D{a}' if (b, a) in dom_hard else 'None (parallel, contract first)')
    G.append(f'| D{a} {BYNUM[a]["ab"]} | D{b} {BYNUM[b]["ab"]} | {w} | {r} | {order} |')
if dom_dropped:
    G += ['', 'Ordering cycles broken by dropping the weakest link: ' + '; '.join(f'D{a} needs D{b} ({w} requirements)' for a, b, w in dom_dropped) + '.']
# XD consistency
decl = collections.defaultdict(lambda: dict(by=set(), ids=[]))
for d in D.values():
    for x in d['xd']:
        for s in x['src']:
            for t in x['dst']:
                if s != t and d['num'] in (s, t):
                    decl[(s, t)]['by'].add(d['num'])
                    decl[(s, t)]['ids'].append(x['id'])
G += ['', '## 3. Declared cross-domain dependencies (section 17.4)', '',
      f'The specifications declare {sum(len(d["xd"]) for d in D.values())} cross-domain dependencies. Each row below is one provider-to-consumer pair. '
      'A pair should be declared by both specifications; where only one declares it, the other specification does not acknowledge the dependency and the contract needs confirming.', '',
      '| Provider | Consumer | Declared by provider | Declared by consumer | Dependency rows |', '|---|---|---|---|---|']
one_sided = 0
for (s, t), v in sorted(decl.items()):
    ps, cs = s in v['by'], t in v['by']
    one_sided += (ps != cs)
    G.append(f'| D{s} {BYNUM[s]["ab"]} | D{t} {BYNUM[t]["ab"]} | {"Yes" if ps else "**No**"} | {"Yes" if cs else "**No**"} | {", ".join(link_id(i, 1) for i in sorted(set(v["ids"])))} |')
G += ['', f'{one_sided} of {len(decl)} pairs are declared by one side only.', '',
      '## 4. Module sequence within each domain', '',
      'A module "needs" another module of its domain when its overview or its requirements name it as upstream. The order uses the same rule as for domains, with the module overview\'s own dependency list counted double. '
      'This ordering is lower-confidence than the domain sequence: the counts are small, so a single mention can move a module, and where the text is circular the weakest link is dropped. Reviewed 2026-11-24 on the owners\' behalf: the session plan does not build in wave order; it orders sessions by the upstream modules each requirement names, so the waves are a guide. '
      'Modules in the same wave of a domain can be built in parallel once the domains they need are available.', '']
mrows = []
for d in order_domains:
    G += [f'### D{d["num"]} {d["ab"]} – {d["name"]}', '', '| Wave | Module | Name | Needs modules first | Needs domains (requirements naming each) |', '|---|---|---|---|---|']
    for m in sorted(d['mods'], key=lambda m: (m['layer'], m['id'])):
        G.append(f'| {m["layer"] + 1} | {link_id(m["id"], 1)} | {td(m["name"])} | {", ".join(m["hard"]) or "–"} | '
                 f'{", ".join(f"D{n}: {w}" for n, w in sorted(m["needs_dom"].items())) or "–"} |')
        mrows.append([d['num'], d['ab'], dom_layer[d['num']] + 1, m['id'], m['name'], m['layer'] + 1, ' '.join(m['hard']),
                      ' '.join(f'{k}:{v}' for k, v in sorted(m['needs_mod'].items())), ' '.join(f'D{k}:{v}' for k, v in sorted(m['needs_dom'].items()))])
    mm = sorted((a, b, w, r) if a < b else (b, a, r, w) for a, b, w, r in d['mod_mutual']
                if (a, b) not in d['mod_hard'] and (b, a) not in d['mod_hard'])
    if mm:
        G += ['', 'Two-way module dependencies with no order set: ' + '; '.join(f'{a} ↔ {b} ({w} / {r})' for a, b, w, r in mm) + '.']
    if d['mod_dropped']:
        G += ['', 'Cycles broken by dropping the weakest link: ' + '; '.join(f'{a} needs {b} ({w})' for a, b, w in d['mod_dropped']) + '.']
    G.append('')
G += ['## 5. Limits of this extraction', '',
      '- **Text-derived.** A dependency exists here only if a specification names the module or domain. Unstated dependencies are not found.',
      '- **Domain-level granularity across domains.** Requirements name other domains, not other domains\' modules, so cross-domain edges cannot be resolved to a specific module without reading the requirement.',
      '- **Need is not the same as blocked.** Many upstream needs can be met by an agreed contract and a stub; the sequencing step decides which are true blockers.',
      '- **Counts are a weight, not an effort measure.**', '',
      'Data: [data/domain-dependencies.csv](../data/domain-dependencies.csv), [data/module-dependencies.csv](../data/module-dependencies.csv), [data/declared-dependencies.csv](../data/declared-dependencies.csv).']
write('delivery/dependency-graph.md', G)
write_csv('data/domain-dependencies.csv', ['domain_no', 'domain', 'wave', 'needs_domain_no', 'needs_domain', 'requirements_naming_it', 'reverse_count', 'sets_order'],
          [[a, BYNUM[a]['ab'], dom_layer[a] + 1, b, BYNUM[b]['ab'], w, dom_need[b].get(a, 0), 'yes' if (a, b) in dom_hard else 'no']
           for a in range(1, 11) for b, w in sorted(dom_need[a].items())])
write_csv('data/module-dependencies.csv', ['domain_no', 'domain', 'domain_wave', 'module_id', 'module', 'module_wave', 'build_after', 'needs_modules_weighted', 'needs_domains_weighted'], mrows)
write_csv('data/declared-dependencies.csv', ['dependency_id', 'declared_in', 'provider', 'consumer', 'information_or_capability', 'type'],
          [[x['id'], d['ab'], x['src_text'], x['dst_text'], x['what'], x['type']] for d in D.values() for x in d['xd']])

# ------------------------------------------------------------------ 03 blocking decisions
THEMES = [('Medication and pharmacy ownership', r'medication|pharmacy|formulary|dispens'),
          ('Service tiers and availability targets', r'\btier'),
          ('Consent and privacy', r'\bconsent|privacy'),
          ('Documents, legal record and retention', r'document|legal record|retention|legal hold'),
          ('Patient identity and MPI', r'\bMPI\b|patient identity|identity[- ]proof|identity steward|merge'),
          ('Inventory, stock and supply chain', r'inventory|\bstock|supply|procurement'),
          ('Nursing and bedside', r'nursing|bedside'),
          ('AI and automation', r'\bAI\b|automat'),
          ('Offline, downtime and degraded mode', r'offline|downtime|degraded'),
          ('Pathways and evidence', r'pathway|guideline|evidence'),
          ('Ownership of a requirement or boundary', r'owner|boundary|primary|which domain'),
          ('Terminology, coding and master data', r'terminolog|coding|master data|code system'),
          ('Scheduling and resources', r'schedul|calendar|appointment'),
          ('Results and release to patients', r'result|release')]
allfr = {fr['id']: (fr, d) for d in D.values() for fr in d['frs']}
decs = []
for d in D.values():
    for dec in d['decs']:
        refs = [fr for fr in d['frs'] if dec['id'] in fr['decs']]
        must = [fr for fr in refs if fr['priority'] == 'Must']
        mods = sorted({fr['mod'] for fr in refs})
        wave = min((d['mod_layer'][m] + 1 for m in mods), default=None)
        cls = 'R' if dec['status'].lower().startswith('resolved') else ('A' if must else ('B' if refs else 'C'))
        themes = [n for n, rx in THEMES if re.search(rx, dec['decision'], re.I)]
        dec.update(dom=d, refs=refs, must=must, mods=mods, wave=wave, cls=cls, themes=themes, dwave=dom_layer[d['num']] + 1)
        decs.append(dec)
decs.sort(key=lambda x: (x['cls'], x['dwave'], x['wave'] or 99, -len(x['must']), x['id']))
cc = collections.Counter(x['cls'] for x in decs)
CL = {'A': 'A – blocks Must requirements', 'B': 'B – affects Should / Could requirements only', 'C': 'C – cited by no functional requirement'}
K = [GENERATED, '', NAV + ' / Blocking decisions', '', '# Blocking Decisions', '',
     f'The ten specifications record {len(decs)} decisions in section 18.3, of which {cc["R"]} are resolved and {len(decs) - cc["R"]} are open. This page ranks the open ones by what they hold up, so the ones that block the earliest work are settled first.', '',
     '## 1. Classification', '', '| Class | Meaning | Decisions |', '|---|---|---|',
     f'| A | Cited by at least one Must requirement. The requirement cannot be built to its final form until the decision is made. | {cc["A"]} |',
     f'| B | Cited only by Should or Could requirements. | {cc["B"]} |',
     f'| C | Cited by no functional requirement. Typically architecture, governance, service-level or ownership decisions; they may still block design and need a manual read. | {cc["C"]} |', '',
     'Within a class, decisions are ordered by the domain wave and module wave of the earliest work they touch (see [the dependency graph](../delivery/dependency-graph.md)), then by the number of Must requirements citing them.', '',
     'Every decision still carries the status recorded in its specification. All specifications state a working position for each decision, so work can proceed on that position at the risk of rework if the decision goes the other way.', '',
     '## 2. Decisions by domain and class', '', '| Domain | Wave | A | B | C | Resolved | Total |', '|---|---|---|---|---|---|---|']
for d in order_domains:
    c = collections.Counter(x['cls'] for x in decs if x['dom'] is d)
    K.append(f'| {dom_link(d["num"], 1)} | {dom_layer[d["num"]] + 1} | {c["A"]} | {c["B"]} | {c["C"]} | {c["R"]} | {sum(c.values())} |')
K += ['', '## 3. Cross-domain themes', '',
      'Several specifications record the same question from their own side. Themes are assigned by keyword from the decision text, so a decision can appear under more than one theme and the grouping was reviewed 2026-11-24. Every decision in the register is now settled, so the themes only group the record. '
      'A theme raised by several domains is best settled once, by one owner.', '', '| Theme | Domains | Decisions | Class A | Decision IDs |', '|---|---|---|---|---|']
for name, _ in THEMES:
    xs = [x for x in decs if name in x['themes'] and x['cls'] != 'R']
    if not xs:
        continue
    doms = sorted({x['dom']['num'] for x in xs})
    K.append(f'| {name} | {", ".join(f"D{n}" for n in doms)} | {len(xs)} | {sum(1 for x in xs if x["cls"] == "A")} | {", ".join(link_id(x["id"], 1) for x in sorted(xs, key=lambda x: x["id"]))} |')
for cls in 'ABC':
    K += ['', f'## {3 + "ABC".index(cls) + 1}. Class {CL[cls]}', '']
    if cls == 'C':
        K += ['| Decision | Domain wave | Decision required | Recommendation in the specification | Decision owner | Status |', '|---|---|---|---|---|---|']
    else:
        K += ['| Decision | Domain wave | Earliest module wave | Decision required | Recommendation in the specification | Decision owner | Status | Requirements citing it (Must in bold) |', '|---|---|---|---|---|---|---|---|']
    for x in [x for x in decs if x['cls'] == cls]:
        base = f'| {link_id(x["id"], 1)} | {x["dwave"]} |'
        if cls != 'C':
            base += f' {x["wave"]} |'
        base += f' {td(x["decision"])} | {td(x["rec"])} | {td(x["owner"])} | {td(x["status"])} |'
        if cls != 'C':
            base += ' ' + ', '.join((f'**{link_id(fr["id"], 1, fr["file"])}**' if fr['priority'] == 'Must' else link_id(fr['id'], 1, fr['file'])) for fr in x['refs']) + ' |'
        K.append(base)
K += ['', '## 7. Resolved decisions', '', f'The {cc["R"]} resolved decisions are listed once, with their outcomes, in the [decision plan](decision-plan.md) under their themes, and in section 18.3 of each specification.']
K += ['', '## 8. Limits of this extraction', '',
      '- **Citation is the test.** A decision is class A only because a Must requirement cites its identifier. A decision that blocks work but is not cited by a requirement lands in class C.',
      '- **No judgement of reversibility.** The classification does not say how costly it is to proceed on the working position and change later. That assessment belongs to the sequencing step.',
      f'- **Known gaps and assumptions are not ranked here.** The specifications also record {sum(d["gap_count"] for d in D.values())} known gaps and {sum(d["asm_count"] for d in D.values())} assumptions in sections 18.4 and 18.1. {sum(d["gap_closed"] for d in D.values())} of the gaps are closed, most of them on common practice; their values (thresholds, retention periods, targets) are defaults that governance may change before go-live.',
      '', 'Data: [data/decisions.csv](../data/decisions.csv).']
write('decisions/blocking-decisions.md', K)
write_csv('data/decisions.csv', ['decision_id', 'domain', 'domain_wave', 'class', 'earliest_module_wave', 'must_requirements', 'all_requirements', 'modules',
                                 'themes', 'decision_required', 'options', 'recommendation', 'owner', 'status'],
          [[x['id'], x['dom']['ab'], x['dwave'], x['cls'], x['wave'] or '', ' '.join(f['id'] for f in x['must']), ' '.join(f['id'] for f in x['refs']),
            ' '.join(x['mods']), '; '.join(x['themes']), x['decision'], x['options'], x['rec'], x['owner'], x['status']] for x in decs])

print('domains', len(D), 'modules', tot['mods'], 'requirements', tot['frs'], 'decisions', len(decs), dict(cc))
print('domain waves:', {f'D{n}': dom_layer[n] + 1 for n in sorted(dom_layer)})
print('two-way domain pairs:', len(seenp), 'cycles broken:', dom_dropped, 'one-sided declared pairs:', one_sided, 'of', len(decl))
