#!/usr/bin/env python3
"""Build the consolidated screen inventory from section 6 of every domain specification.

Reads   docs/domain_specs/*/06-user-interface.md (catalogue 6.2 and screen detail 6.3),
        docs/domain_specs/*/02-domain-overview.md (actor names),
        data/slices.csv (which slice and stage releases each requirement),
        tools/definitions/screens_def.py (hand-authored patterns, overlaps and form factors).
Writes  docs/design/screen-inventory.md and data/screens.csv.

Run after build_slices.py:  python3 docs/implementation_plan/tools/build_screens.py
"""
import re, os, csv, sys, glob, collections
sys.dont_write_bytecode = True
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, 'definitions'))
from screens_def import PATTERNS, OVERLAPS, FORM, DEFER  # noqa: E402
from roles_def import ROLES  # noqa: E402
DROLES = collections.defaultdict(list)
for _r in ROLES:
    for _x in _r['screens'].split(','):
        if _x.strip():
            DROLES['UI-' + _x.strip()].append(_r['id'])
RTITLE = {r['id']: r['title'] for r in ROLES}

PLAN = os.path.dirname(HERE)
DESIGN = os.path.join(os.path.dirname(PLAN), 'design')
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)}
GENERATED = '<!-- Generated by tools/build_screens.py from docs/domain_specs and implementation_plan/tools/definitions/screens_def.py. Edit screens_def.py, not this file. -->'
STAGES = {1: 'Platform foundation', 2: 'Patient administration', 3: 'Core clinical', 4: 'Ancillary and medication',
          5: 'Revenue and enterprise operations', 6: 'Analytics and optimization'}


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


def expand(text, prefix):
    """Expand 'ACT-ANC-009 to ACT-ANC-012' and 'MOD-PEX-003, 004, 005' into full identifiers."""
    out, last = [], None
    text = re.sub(rf'({prefix}-[A-Z]+-)(\d{{3}}) to {prefix}-[A-Z]+-(\d{{3}})',
                  lambda m: ', '.join(f'{m.group(1)}{n:03d}' for n in range(int(m.group(2)), int(m.group(3)) + 1)), text)
    for tok in re.findall(rf'{prefix}-[A-Z]+-\d{{3}}|(?<![\w-])\d{{3}}(?![\w-])', text):
        if tok.startswith(prefix):
            last = tok[:-3]
            out.append(tok)
        elif last:
            out.append(last + tok)
    return list(dict.fromkeys(out))


# ---- slices: requirement -> slice, module -> slices ----
SL = list(csv.DictReader(open(os.path.join(PLAN, 'data', 'slices.csv'))))
ORDER = list(dict.fromkeys(r['slice'] for r in SL))
PHASE = {r['slice']: int(r['phase']) for r in SL}
FR_SLICE = {r['requirement_id']: r['slice'] for r in SL}
AFTER = {r['slice']: r['after'].split() for r in SL}


def later(a, b):
    """True when slice b comes after slice a, directly or through other slices."""
    todo, seen = list(AFTER.get(b, [])), set()
    while todo:
        x = todo.pop()
        if x == a:
            return True
        if x not in seen:
            seen.add(x)
            todo += AFTER.get(x, [])
    return False


MOD_SLICES = collections.defaultdict(set)
for r in SL:
    MOD_SLICES[r['module_id']].add(r['slice'])
skey = lambda s: (PHASE[s], ORDER.index(s))

# ---- pattern membership ----
PAT = {}
for p in PATTERNS:
    for x in p['ids'].split(','):
        uid = 'UI-' + x.strip()
        if uid in PAT:
            sys.exit(f'{uid} is in two patterns: {PAT[uid]} and {p["id"]}')
        PAT[uid] = p['id']
PTITLE = {p['id']: p['title'] for p in PATTERNS}

# ---- parse the specifications ----
screens = []
for ab in ABBR:
    d = os.path.join(SPECS, FOLDER[ab])
    actors = {}
    for line in open(os.path.join(d, '02-domain-overview.md')):
        m = re.match(r'\| <a id="act-[a-z]+-\d+"></a>(ACT-[A-Z]+-\d{3}) \| ([^|]+) \|', line)
        if m:
            actors[m.group(1)] = plain(m.group(2))
    text = open(os.path.join(d, '06-user-interface.md')).read()
    # screen detail: requirements cited under each '### Screen UI-...' heading
    detail = {}
    for m in re.finditer(r'^### Screen (UI-[A-Z]+-\d{3}):.*?(?=^### |^## |\Z)', text, re.S | re.M):
        detail[m.group(1)] = list(dict.fromkeys(re.findall(r'FR-[A-Z]+-[A-Z]+-\d{3}', m.group(0))))
    cat = text[text.index('## 6.2'):text.index('## 6.3')]
    for line in cat.splitlines():
        cells = [c.strip() for c in line.strip().strip('|').split('|')]
        if len(cells) < 5 or not re.search(r'UI-[A-Z]+-\d{3}', cells[0]):
            continue
        uid = re.search(r'UI-[A-Z]+-\d{3}', cells[0]).group(0)
        mods = expand(plain(cells[2]), 'MOD')
        role = plain(cells[3])
        for a in expand(role, 'ACT'):
            pass
        role = re.sub(r'(ACT-[A-Z]+-)(\d{3}) to ACT-[A-Z]+-(\d{3})',
                      lambda m: ', '.join(f'{m.group(1)}{n:03d}' for n in range(int(m.group(2)), int(m.group(3)) + 1)), role)
        ids = expand(role, 'ACT')
        if ids:
            rest = re.sub(r'ACT-[A-Z]+-\d{3}|(?<![\w-])\d{3}(?![\w-])', '', role)
            rest = [x.strip() for x in re.split(r'[,;]', rest) if x.strip()]
            role = '; '.join([actors.get(a, a) for a in ids] + rest)
        frs = detail.get(uid, [])
        src = 'Requirements' if frs else 'Modules'
        if not frs:
            frs = [r['requirement_id'] for r in SL if r['module_id'] in mods]
        cnt = collections.Counter(FR_SLICE[f] for f in frs if f in FR_SLICE)
        sl = sorted(cnt, key=skey)
        # main slice: the one that releases most of the screen's requirements (earliest on a tie)
        main = min(cnt, key=lambda x: (-cnt[x], skey(x))) if cnt else ''
        deferred = None
        if uid in DEFER:
            to, why = DEFER[uid]
            if to not in PHASE or not main or not later(main, to):
                sys.exit(f'screens_def.py: DEFER moves {uid} to {to}, which does not come after its main slice {main or "(none)"}')
            deferred = dict(frm=main, why=why)
            main = to
            sl = sorted(set(sl) | {to}, key=skey)
        if uid not in PAT:
            sys.exit(f'{uid} is not in any pattern in screens_def.py')
        pat = PAT[uid]
        form = FORM.get(uid) or ('Component' if pat == 'P01' else 'Patient web and mobile' if pat == 'P13' else 'Workstation')
        screens.append(dict(ui_id=uid, screen=plain(cells[1]), domain=FOLDER[ab], abbr=ab, modules=mods, roles=role,
                            purpose=plain(cells[4]), pattern=pat, form=form,
                            detail='Detailed' if uid in detail else 'Catalogue only',
                            stage=PHASE[main] if main else None, first=main, earliest=sl[0] if sl else '', slices=sl, source=src,
                            deferred=deferred))

known = {s['ui_id'] for s in screens}

# screen briefs written for catalogue-only screens (screen-briefs/*.md, one '<a id="ui-...">' anchor per brief)
BRIEF = {}
for fn in sorted(glob.glob(os.path.join(DESIGN, 'screen-briefs', '*.md'))):
    for a in re.findall(r'<a id="(ui-[a-z]+-\d{3})"></a>', open(fn).read()):
        BRIEF[a.upper()] = f'screen-briefs/{os.path.basename(fn)}#{a}'
bad = sorted(set(BRIEF) - known)
if bad:
    sys.exit(f'screen briefs for unknown screens: {bad}')
for s in screens:
    if s['detail'] == 'Catalogue only' and s['ui_id'] in BRIEF:
        s['detail'] = 'Brief'
extra = (set(PAT) | set(DEFER)) - known
if extra:
    sys.exit(f'screens_def.py names screens that are not in the specifications: {sorted(extra)}')
for o in OVERLAPS:
    bad = [x.strip() for x in o['ids'].split(',') if 'UI-' + x.strip() not in known]
    if bad:
        sys.exit(f'overlap "{o["title"]}" names unknown screens: {bad}')
BYID = {s['ui_id']: s for s in screens}
OVER = collections.defaultdict(list)
for o in OVERLAPS:
    for x in o['ids'].split(','):
        OVER['UI-' + x.strip()].append(o['title'])
screens.sort(key=lambda s: (s['stage'] or 9, skey(s['first']) if s['first'] else (9, 99), s['pattern'], s['ui_id']))


def ui(uid, text=None):
    s = BYID[uid]
    return f"[{text or uid}](../domain_specs/{s['domain']}/06-user-interface.md#{uid.lower()})"


def sl_link(sid):
    return f"[{sid}](../implementation_plan/delivery/slices/{sid.split('-')[0]}.md#{sid.lower()})"


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


# ---- Markdown ----
n = len(screens)
nd = sum(s['detail'] == 'Detailed' for s in screens)
nb = sum(s['detail'] == 'Brief' for s in screens)
O = [GENERATED, '', '[Design](README.md) / Screen inventory', '', '# Screen Inventory', '',
     f'One list of every screen, workspace and shared component named in section 6 of the ten domain specifications: '
     f'{n} entries, of which {nd} have a screen-level description (components, actions, validation rules and navigation) '
     f'and {n - nd} have a catalogue entry only. Each entry is mapped to the stage and slice that delivers most of it, '
     'so the list can be used as a design backlog in delivery order.', '',
     'How to read it:', '',
     '- **Stage and main slice** are derived, not stated in the specifications. The main slice is the one that releases most of '
     'the requirements behind the screen; "Other slices" lists the rest, in delivery order, so a slice listed there before the main '
     'slice needs an early, partial version of the screen. Where a screen has a detailed description, the requirements are those it '
     'cites; otherwise all requirements of its modules. The "Mapped from" column says which. A few screens are deliberately moved to a later '
     'main slice; they are marked "moved" and listed with the reason in [section 2](#deferred).',
     '- **Pattern** groups screens that should share one design ([section 3](#s3)). Patterns, overlaps and form factors '
     'are design judgements made in `tools/definitions/screens_def.py` of the implementation plan, not specification content.',
     '- **Design roles** are the consolidated roles of [user-roles.md](user-roles.md). The roles as each specification '
     'wrote them are kept in `implementation_plan/data/screens.csv`.', '',
     '<a id="s1"></a>', '', '## 1. Summary', '']
pats = [p['id'] for p in PATTERNS]
O += ['| Stage | Screens | ' + ' | '.join(pats) + ' |', '|---|---|' + '---|' * len(pats)]
for st in list(STAGES) + [None]:
    rows = [s for s in screens if s['stage'] == st]
    if not rows:
        continue
    label = f'{st} {STAGES[st]}' if st else 'Not mapped'
    O.append(f'| {label} | {len(rows)} | ' + ' | '.join(str(sum(s['pattern'] == p for s in rows) or '') for p in pats) + ' |')
O.append(f'| **Total** | **{n}** | ' + ' | '.join(f"**{sum(s['pattern'] == p for s in screens)}**" for p in pats) + ' |')
O += ['', 'Pattern names: ' + '; '.join(f"{p['id']} {p['title']}" for p in PATTERNS) + '.', '',
      '| Domain | Screens | Detailed | Screen brief | Catalogue only |', '|---|---|---|---|---|']
for ab in ABBR:
    rows = [s for s in screens if s['abbr'] == ab]
    k = sum(s['detail'] == 'Detailed' for s in rows)
    b = sum(s['detail'] == 'Brief' for s in rows)
    O.append(f"| [{FOLDER[ab]}](../domain_specs/{FOLDER[ab]}/06-user-interface.md) | {len(rows)} | {k} | {b or ''} | {len(rows) - k - b} |")

O += ['', '<a id="s2"></a>', '', '## 2. Design backlog in delivery order', '',
      'Within a stage, screens are in the order of their main slice. Design the pattern P01 components of a stage first.', '']
for st in list(STAGES) + [None]:
    rows = [s for s in screens if s['stage'] == st]
    if not rows:
        continue
    O += [f'### Stage {st}: {STAGES[st]} ({len(rows)})' if st else f'### Not mapped to a slice ({len(rows)})', '',
          '| Screen | Name | Domain | Pattern | Form factor | Design roles | Main slice | Other slices | Mapped from | Specification | Overlap |',
          '|---|---|---|---|---|---|---|---|---|---|---|']
    for s in rows:
        O.append(f"| {ui(s['ui_id'])} | {td(s['screen'])} | {s['domain']} | [{s['pattern']}](#{s['pattern'].lower()}) | {s['form']} | "
                 f"{', '.join(f'[{x}](user-roles.md#{x.lower()})' for x in DROLES[s['ui_id']])} | {sl_link(s['first']) if s['first'] else ''}{' (moved)' if s['deferred'] else ''} | {' '.join(sl_link(x) for x in [x for x in s['slices'] if x != s['first']])} | "
                 f"{s['source']} | {('[Brief](' + BRIEF[s['ui_id']] + ')') if s['detail'] == 'Brief' else s['detail']} | {td('; '.join(OVER.get(s['ui_id'], [])))} |")
    O.append('')
moved = [s for s in screens if s['deferred']]
O += ['<a id="deferred"></a>', '', f'### Screens moved to a later slice ({len(moved)})', '',
      'These screens would be released in the slice shown under "Derived", which releases most of their requirements. They are moved to a later main slice '
      'by the DEFER table of `tools/definitions/screens_def.py`, so that the derived slice stays thin. The requirements stay in the derived slice; '
      'only the screen waits.', '',
      '| Screen | Name | Derived | Moved to | Reason |', '|---|---|---|---|---|']
for s in moved:
    O.append(f"| {ui(s['ui_id'])} | {td(s['screen'])} | {sl_link(s['deferred']['frm'])} | {sl_link(s['first'])} | {td(s['deferred']['why'])} |")
O.append('')

O += ['<a id="s3"></a>', '', '## 3. Design patterns', '',
      'Screens in one pattern solve the same interaction problem. Designing the pattern once, then each screen as a variant, '
      'is what keeps terminology, colour meaning and save states consistent across domains (PRS section 11.3).', '']
for p in PATTERNS:
    rows = [s for s in screens if s['pattern'] == p['id']]
    O += [f'<a id="{p["id"].lower()}"></a>', '', f"### {p['id']} {p['title']} ({len(rows)})", '', p['note'], '',
          '| Screen | Name | Stage | Main slice |', '|---|---|---|---|']
    for s in rows:
        O.append(f"| {ui(s['ui_id'])} | {td(s['screen'])} | {s['stage'] or ''} | {sl_link(s['first']) if s['first'] else ''} |")
    O.append('')

O += ['<a id="s4"></a>', '', '## 4. Overlaps to resolve', '',
      'The specifications were written per domain, so some screens describe the same thing from two sides. '
      'None is a contradiction; each needs one shared design and a named owner before detailed design starts. '
      'Each overlap is resolved in the design readiness page of the batch that first reaches it: '
      '[first](design-readiness/first-batch-design-readiness.md#s2), [second](design-readiness/second-batch-design-readiness.md#s2), '
      '[third](design-readiness/third-batch-design-readiness.md#s2), [fourth](design-readiness/fourth-batch-design-readiness.md#s2) '
      'and [fifth](design-readiness/fifth-batch-design-readiness.md#s2) batch.', '',
      '| No. | Overlap | Screens | What to do | Resolution |', '|---|---|---|---|---|']
for i, o in enumerate(OVERLAPS, 1):
    ids = ['UI-' + x.strip() for x in o['ids'].split(',')]
    r = o.get('resolved')
    O.append(f"| {i} | {o['title']} | {', '.join(ui(x) for x in ids)} | {td(o['action'])} | "
             + (f"[{r}](design-readiness/{o.get('doc', 'first-batch-design-readiness.md')}#{r.lower()})" if r else 'Open') + ' |')

unm = [s for s in screens if not s['first']]
O += ['', '<a id="s5"></a>', '', '## 5. Limits of this inventory', '',
      f'- **{n - nd} screens have no screen-level description in the specifications.** {nb} of them now have a '
      '[screen brief](screen-briefs/README.md), written from the functional requirements of their modules. For the other '
      f'{n - nd - nb}, the components, actions and validation rules must be worked out the same way before detailed design.',
      f'- **{len(unm)} screens could not be mapped to a slice**' + (': ' + ', '.join(ui(s['ui_id']) for s in unm) + '.' if unm else '.'),
      '- **The inventory lists only what the specifications name.** Screens the specifications imply but do not list '
      '(for example a role home page for each workforce role) are not included. Prints, labels and wristbands are designed once in '
      '[Shell 14](application-shell.md#s14), and the standard screen states in [Shell 13](application-shell.md#s13).',
      '- **Diagnostic department screens are all in scope.** DEC-ANC-001 was resolved on 16 November 2026: laboratory, radiology '
      'workflow, pathology and blood bank are built, so every workbench in the inventory is designed. The imaging archive '
      '(dcm4chee) and the image viewers (OHIF, Weasis) are integrated open-source components, not HIS screens ([technology stack](../implementation_plan/decisions/technology-stack.md)).', '']
open(os.path.join(DESIGN, 'screen-inventory.md'), 'w').write('\n'.join(O))

# ---- CSV ----
cols = ['ui_id', 'screen', 'domain', 'pattern', 'pattern_title', 'form_factor', 'design_roles', 'roles', 'purpose', 'modules',
        'stage', 'main_slice', 'slices', 'mapped_from', 'specification_detail', 'overlaps']
rows_out = [[s['ui_id'], s['screen'], s['domain'], s['pattern'], PTITLE[s['pattern']], s['form'], ' '.join(DROLES[s['ui_id']]), s['roles'], s['purpose'],
             ' '.join(s['modules']), s['stage'] or '', s['first'], ' '.join(s['slices']), s['source'], s['detail'],
             '; '.join(OVER.get(s['ui_id'], []))] for s in screens]
with open(os.path.join(PLAN, 'data', 'screens.csv'), 'w', newline='') as f:
    w = csv.writer(f)
    w.writerow(cols)
    w.writerows(rows_out)

print(f'screens: {n}  detailed: {nd}  unmapped: {len(unm)}  wrote design/screen-inventory.md, data/screens.csv')
