#!/usr/bin/env python3
"""Build the consolidated user role list from the actors in section 2 of every domain specification.

Reads   docs/domain_specs/*/02-domain-overview.md (actor tables),
        data/screens.csv (from build_screens.py),
        tools/definitions/roles_def.py (hand-authored roles).
Writes  docs/design/user-roles.md, data/roles.csv, data/role-actors.csv and data/role-screens.csv.

Run after build_screens.py:  python3 docs/implementation_plan/tools/build_roles.py
"""
import re, os, csv, sys, collections
sys.dont_write_bytecode = True
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, 'definitions'))
from roles_def import FAMILIES, FORMS, FORM_DESIGN, ROLES, SYSTEM_ACTORS  # noqa: E402

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_roles.py from docs/domain_specs and implementation_plan/tools/definitions/roles_def.py. Edit roles_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'}
FREQS = ['Continuous', 'Frequent', 'Daily', 'Periodic', 'On event']


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


def ids(text, prefix):
    return [f'{prefix}-{x.strip()}' for x in text.split(',') if x.strip()]


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


# ---- actors from the specifications ----
ACT = {}
for ab in ABBR:
    for line in open(os.path.join(SPECS, FOLDER[ab], '02-domain-overview.md')):
        m = re.match(r'\| <a id="act-[a-z]+-\d+"></a>(ACT-[A-Z]+-\d{3}) \|([^|]*)\|([^|]*)\|([^|]*)\|', line)
        if m:
            ACT[m.group(1)] = dict(name=plain(m.group(2)), activities=plain(m.group(4)), domain=FOLDER[ab])

# ---- screens ----
SCR = {r['ui_id']: r for r in csv.DictReader(open(os.path.join(PLAN, 'data', 'screens.csv')))}

# ---- validation ----
err = []
owner = {}
for r in ROLES:
    for a in ids(r['actors'], 'ACT'):
        if a not in ACT:
            err.append(f"{r['id']}: unknown actor {a}")
        elif a in owner:
            err.append(f"{a} is in {owner[a]} and {r['id']}")
        owner[a] = r['id']
    for s in ids(r['screens'], 'UI'):
        if s not in SCR:
            err.append(f"{r['id']}: unknown screen {s}")
    if r['family'] not in FAMILIES:
        err.append(f"{r['id']}: unknown family {r['family']}")
    if r['form'] not in FORMS:
        err.append(f"{r['id']}: unknown form factor {r['form']}")
    if r['freq'] not in FREQS:
        err.append(f"{r['id']}: unknown frequency {r['freq']}")
system = ids(SYSTEM_ACTORS, 'ACT')
for a in system:
    if a not in ACT:
        err.append(f'unknown system actor {a}')
    elif a in owner:
        err.append(f'{a} is both a system actor and in {owner[a]}')
missing = sorted(set(ACT) - set(owner) - set(system))
if missing:
    err.append('actors in no role and not listed as system actors: ' + ', '.join(missing))
used = {s for r in ROLES for s in ids(r['screens'], 'UI')}
unused = sorted(set(SCR) - used)
if unused:
    err.append('screens used by no role: ' + ', '.join(unused))
if err:
    sys.exit('\n'.join(err))

# ---- derived ----
for r in ROLES:
    r['actor_ids'] = ids(r['actors'], 'ACT')
    r['screen_ids'] = ids(r['screens'], 'UI')
    # shared components (pattern P01) arrive with stage 1 for everyone; they do not set when a role needs its own screens
    own = [s for s in r['screen_ids'] if SCR[s]['pattern'] != 'P01'] or r['screen_ids']
    st = [int(SCR[s]['stage']) for s in own if SCR[s]['stage']]
    r['first_stage'] = min(st) if st else None
    r['domains'] = sorted({ACT[a]['domain'] for a in r['actor_ids']})
human = sum(len(r['actor_ids']) for r in ROLES)
ROLE_OF_SCREEN = collections.defaultdict(list)
for r in ROLES:
    for s in r['screen_ids']:
        ROLE_OF_SCREEN[s].append(r['id'])


def act(a):
    return f"[{a}](../domain_specs/{ACT[a]['domain']}/02-domain-overview.md#{a.lower()})"


def ui(s):
    return f"[{s}](../domain_specs/{SCR[s]['domain']}/06-user-interface.md#{s.lower()})"


def role_link(r):
    return f"[{r['id']}](#{r['id'].lower()})"


# ---- Markdown ----
O = [GENERATED, '', '[Design](README.md) / User roles', '', '# User Roles', '',
     f'One role list for the whole system. The ten specifications define {len(ACT)} actors in their section 2; '
     f'{len(system)} are systems and services, and the other {human} are people. Those {human} are merged here into '
     f'{len(ROLES)} roles where different specifications name the same job, for example the physician who is the '
     '"responsible clinician" in Domain 6 and the "treating clinician" in Domains 7 and 9.', '',
     'For each role the page gives its main tasks, how often they are done, where and on what device, and the input method, '
     'screen density and form factor that follow. It then lists the screens the role uses from the '
     '[screen inventory](screen-inventory.md), and the stage at which the role first needs a screen of its own, which is when its '
     'representatives must be recruited for design and usability testing (SAFE-006, NFR-010).', '',
     '**Status of this content.** The merge of actors, the screens per role and the work context are design proposals made in '
     '`tools/definitions/roles_def.py` of the implementation plan, drawn from the specifications and normal hospital practice. Frequency, place, devices and input '
     'method must be confirmed by observing real staff before detailed design. Role names here are design roles, not '
     'access-control roles: permissions are defined by Domain 10.', '',
     '<a id="s1"></a>', '', '## 1. Summary', '', '### By family', '',
     '| Family | Roles | Actors merged | First needed at stage |', '|---|---|---|---|']
for f in FAMILIES:
    rs = [r for r in ROLES if r['family'] == f]
    st = [r['first_stage'] for r in rs if r['first_stage']]
    O.append(f"| [{f}](#{'fam-' + re.sub(r'[^a-z]+', '-', f.lower()).strip('-')}) | {len(rs)} | {sum(len(r['actor_ids']) for r in rs)} | {min(st) if st else ''} |")
O.append(f'| **Total** | **{len(ROLES)}** | **{human}** | |')
O += ['', '### By form factor', '',
      'The primary form factor of each role, and what it means for screen design. A role that also works on another device '
      'says so under Devices.', '',
      '| Form factor | Roles | What it means for design |', '|---|---|---|']
for k, v in FORMS.items():
    rs = [r for r in ROLES if r['form'] == k]
    if rs:
        cell = f"{len(rs)} ({', '.join(role_link(r) for r in rs)})"
    else:
        also = [r for r in ROLES if k.lower() in r['devices'].lower()]
        cell = 'None as main device; also used by ' + ', '.join(role_link(r) for r in also)
    O.append(f"| **{k}**: {v} | {cell} | {FORM_DESIGN[k]} |")
O += ['', '### By frequency and density', '',
      '| Frequency | High density | Medium density | Low density |', '|---|---|---|---|']
for fq in FREQS:
    cells = [', '.join(role_link(r) for r in ROLES if r['freq'] == fq and r['density'] == d) for d in ['High', 'Medium', 'Low']]
    O.append(f'| {fq} | ' + ' | '.join(cells) + ' |')
O += ['', 'Frequency: Continuous means many times an hour through the shift; Frequent several times a day; Daily once or a few '
      'times a day; Periodic weekly, monthly or per cycle; On event rare and unplanned. Roles in the top-left cells are the '
      'expert, high-volume users whose screens most repay keyboard shortcuts and dense layouts; roles at the bottom right need '
      'screens that work without training.', '',
      '<a id="s2"></a>', '', '## 2. Role list', '',
      '| Role | Title | Family | Frequency | Form factor | Density | Input | Screens | First stage |', '|---|---|---|---|---|---|---|---|---|']
for r in ROLES:
    O.append(f"| {role_link(r)} | {r['title']} | {r['family']} | {r['freq']} | {r['form']} | {r['density']} | {td(r['input'])} | "
             f"{len(r['screen_ids'])} | {r['first_stage'] or ''} |")

O += ['', '<a id="s3"></a>', '', '## 3. Role details', '']
for f in FAMILIES:
    O += [f"<a id=\"{'fam-' + re.sub(r'[^a-z]+', '-', f.lower()).strip('-')}\"></a>", '', f'### {f}', '']
    for r in [x for x in ROLES if x['family'] == f]:
        O += [f'<a id="{r["id"].lower()}"></a>', '', f"#### {r['id']} {r['title']}", '',
              '| Aspect | Detail |', '|---|---|',
              f"| Main tasks | {td(r['tasks'])} |",
              f"| Frequency | {r['freq']} |",
              f"| Where | {td(r['where'])} |",
              f"| Devices | {td(r['devices'])} |",
              f"| Input | {td(r['input'])} |",
              f"| Density | {r['density']} |",
              f"| Form factor | {r['form']} |",
              f"| Merged actors | {'; '.join(act(a) + ' ' + ACT[a]['name'] for a in r['actor_ids'])} |",
              f"| Screens | {', '.join(ui(s) for s in r['screen_ids']) or 'None in the HIS'} |",
              f"| First needs its own screens at | {('stage ' + str(r['first_stage']) + ' ' + STAGES[r['first_stage']]) if r['first_stage'] else 'No HIS screen'} |"]
        if r.get('notes'):
            O.append(f"| Notes | {td(r['notes'])} |")
        O.append('')

O += ['<a id="s4"></a>', '', '## 4. Usability test participants, by stage', '',
      'Roles grouped by the stage at which they first need a screen of their own (shared components such as sign-on and the task '
      'inbox are left out, because every role meets them in stage 1). The work context of the roles is set from common hospital '
      'practice, so there is no field study before design ([section 6](#s6)); these groups are instead the participants of the '
      'usability tests that check the designs:', '',
      '- **Formative tests** on clickable prototypes during the stage\'s design: 5 to 8 representatives of each group, in rounds, '
      'fixing what each round finds before the next. Recruit them when design of the stage starts.',
      '- **Summative safety tests** (SAFE-006) before the stage\'s release, following the NISTIR 7804 protocol for EHR usability: '
      '15 participants per user group for the roles that perform safety-critical tasks (identifying the patient, ordering, '
      'medication administration, specimen collection, result acknowledgement, merge), scripted tasks, use errors recorded '
      'against the clinical hazard log (SAFE-001).',
      '- What the tests show about a role\'s work context is recorded in `tools/definitions/roles_def.py` of the implementation plan, and this page is rebuilt.', '',
      '| Stage | Roles first needed |', '|---|---|']
for st, name in STAGES.items():
    rs = [r for r in ROLES if r['first_stage'] == st]
    O.append(f"| {st} {name} | {', '.join(role_link(r) + ' ' + r['title'] for r in rs)} |")

O += ['', '<a id="s5"></a>', '', '## 5. Actor-to-role map', '',
      'Every actor in the specifications and the role it is merged into.', '',
      '| Actor | Name in the specification | Role |', '|---|---|---|']
ROLEBY = {r['id']: r for r in ROLES}
for a in sorted(ACT, key=lambda x: (ABBR.index(x.split('-')[1]), x)):
    if a in owner:
        r = ROLEBY[owner[a]]
        O.append(f"| {act(a)} | {td(ACT[a]['name'])} | {role_link(r)} {r['title']} |")
    else:
        O.append(f"| {act(a)} | {td(ACT[a]['name'])} | System actor (no screens) |")

O += ['', '<a id="s6"></a>', '', '## 6. Limits', '',
      '- **Work context comes from common practice, not from a field study.** Frequency, place, devices, input method, density '
      'and form factor are taken from the specifications and common practice in hospital information systems, and were '
      'adopted as the design baseline on 17 November 2026 instead of contextual inquiry before design. They are checked in '
      'the usability tests of [section 4](#s4), in heuristic review of each design against the '
      '[clinical UX safety rules](clinical-ux-safety-rules.md) (CUX-55) by two reviewers, one of them a clinician of the role, '
      'and after go-live through incident reports and the clinical hazard log. A test finding that contradicts a role\'s work '
      'context changes this page through [roles_def.py](../implementation_plan/tools/definitions/roles_def.py).',
      '- **Roles are not access-control roles.** One person may hold several design roles (a charge nurse also works as a ward '
      'nurse; a surgeon is also a physician). Permissions and separation of duties are defined by Domain 10.',
      '- **No numbers of users.** The specifications give none. User counts per role, needed for training and licence planning, '
      'should be collected from the hospital.',
      '- **Some merges are design judgements**, for example combining the NICU and ICU nurse, the stewardship roles of '
      'Domains 8, 9 and 10, and the seven domain configuration roles. They follow common practice, are explained in each '
      'role\'s notes, and are split only if usability tests show the merged roles need different screens.', '']
open(os.path.join(DESIGN, 'user-roles.md'), 'w').write('\n'.join(O))

# ---- CSV ----
with open(os.path.join(PLAN, 'data', 'roles.csv'), 'w', newline='') as fh:
    w = csv.writer(fh)
    w.writerow(['role_id', 'title', 'family', 'frequency', 'form_factor', 'density', 'input', 'where', 'devices', 'tasks',
                'actors', 'screens', 'first_stage', 'notes'])
    for r in ROLES:
        w.writerow([r['id'], r['title'], r['family'], r['freq'], r['form'], r['density'], r['input'], r['where'], r['devices'],
                    r['tasks'], ' '.join(r['actor_ids']), ' '.join(r['screen_ids']), r['first_stage'] or '', r.get('notes', '')])
with open(os.path.join(PLAN, 'data', 'role-actors.csv'), 'w', newline='') as fh:
    w = csv.writer(fh)
    w.writerow(['actor_id', 'actor_name', 'domain', 'role_id'])
    for a in sorted(ACT):
        w.writerow([a, ACT[a]['name'], ACT[a]['domain'], owner.get(a, 'SYSTEM')])
with open(os.path.join(PLAN, 'data', 'role-screens.csv'), 'w', newline='') as fh:
    w = csv.writer(fh)
    w.writerow(['role_id', 'ui_id'])
    for r in ROLES:
        for s in r['screen_ids']:
            w.writerow([r['id'], s])

print(f'roles: {len(ROLES)}  actors: {len(ACT)} ({human} people, {len(system)} systems)  wrote design/user-roles.md, data/roles.csv, data/role-actors.csv, data/role-screens.csv')
