#!/usr/bin/env python3
"""Apply the decision outcomes in decisions/outcomes.csv to the domain specifications and the plan.

Reads   decisions/outcomes.csv                  the recorded outcomes (status, chosen option, settled, who, when)
        tools/definitions/tech_stack.csv        the technology stack rows: item, scope, recommendation, decisions
        tools/definitions/decisions_def.py      which theme each decision is in
        the specifications, section 18.3        each decision's scope and recommendation
Writes  data/decision-register.csv              one row per technology selection and per decision, with its outcome
        docs/domain_specs/*/18-assumptions-decisions-gaps.md   the Status cell of each decision in section 18.3
        decisions/technology-stack.md            the selected technology stack

Run:    python3 docs/implementation_plan/tools/build.py   (runs this script first)

A decision is recorded in one of two ways, by the settled column of outcomes.csv:
  yes  the chosen option settles the decision. Status becomes "Resolved <date> (decision register): <outcome>".
  no   the chosen option only says how or when the decision will be made. The decision stays open and the
       status records the agreed approach.
The date is the date decided, or failing that the date the outcome was recorded. A chosen option reading
"See the Tech stack sheet" takes its outcome from the technology stack rows that name the decision.
"""
import os, re, csv, sys, collections
sys.dont_write_bytecode = True

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, 'definitions'))
import outcomes as oc  # noqa: E402
import decisions_def as dd  # 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)}
GENERATED = '<!-- Generated by tools/apply_decisions.py from decisions/outcomes.csv and tools/definitions/tech_stack.csv. Edit those, not this file. -->'
OUTCOMES_LINK = '../../implementation_plan/decisions/outcomes.csv'


def clean(t):
    t = '' if t is None else str(t)
    t = re.sub(r'\s*\n\s*', ' ', t).strip().rstrip('.')
    return re.sub(r'\s{2,}', ' ', t)


def cell(t):
    return clean(t).replace('|', '/')


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


# ---- read the technology stack rows, the themes, the specification rows and the outcomes ----
OUT = oc.read()
tech, theme = [], {}
for d in oc.read_tech_stack():
    o = OUT.get(oc.tech_id(d['no'])) or sys.exit(f"outcomes.csv has no row {oc.tech_id(d['no'])}")
    tech.append(dict(no=int(d['no']), group=d['group'], item=d['item'], scope=d['scope'],
                     rec=clean(d['recommendation']), chosen=clean(o['chosen_option']),
                     ids=[x.strip() for x in d['decision_ids'].split(';') if x.strip()],
                     stage=d['needed_before_stage'], slice=d['first_slice'], constraints=d['constraints'],
                     status=o['status'], adr=o['adr_reference'], by=o['decided_by'], when=o['date_decided'],
                     notes=re.sub(r'\s+', ' ', o['notes']).strip(), recorded=o['recorded']))
SPEC = {}
for ab in ABBR:
    for row in re.findall(r'^\| <a id="dec-[^\n]*$', open(os.path.join(SPECS, FOLDER[ab], '18-assumptions-decisions-gaps.md')).read(), re.M):
        c = [plain(x.strip()) for x in row.strip().strip('|').split('|')]
        SPEC[c[0]] = dict(scope=c[1], rec=c[3])
for t in dd.THEMES:
    for x in t['ids'].split(','):
        did = 'DEC-' + x.strip()
        o = OUT.get(did) or sys.exit(f'outcomes.csv has no row for {did}, which is in theme {t["id"]}')
        if did not in SPEC:
            sys.exit(f'{did} is in theme {t["id"]} but not in section 18.3 of its specification')
        theme[did] = dict(theme=t['id'], chosen=clean(o['chosen_option']), rec=clean(SPEC[did]['rec']),
                          scope=SPEC[did]['scope'], status=o['status'], adr=o['adr_reference'],
                          by=o['decided_by'], when=o['date_decided'], notes=o['notes'],
                          settled=o['settled'] == 'yes', recorded=o['recorded'])
extra = sorted(set(OUT) - set(theme) - {oc.tech_id(t['no']) for t in tech})
if extra:
    sys.exit('outcomes.csv has rows that are in no theme and no technology stack row: ' + ', '.join(extra))
missing = [k for k, v in theme.items() if not v['chosen']] + [f"Tech stack row {t['no']}" for t in tech if not t['chosen']]
if missing:
    print('No chosen option (left unchanged):', ', '.join(missing))

TECH_BY_ID = collections.defaultdict(list)
for t in tech:
    for i in t['ids']:
        TECH_BY_ID[i].append(t)

# ---- outcome per decision ----
outcome = {}
for did, v in theme.items():
    if not v['chosen']:
        continue
    if v['chosen'] == oc.FROM_TECH:
        if not TECH_BY_ID[did]:
            sys.exit(f'{did}: chosen option says "{oc.FROM_TECH}" but no technology stack row names it')
        text = '; '.join(f"{t['item']}: {t['chosen']}" for t in TECH_BY_ID[did]) + '. Each selection is recorded as an architecture decision record'
    else:
        text = v['chosen']
    kind = 'Resolved' if v['settled'] else 'Open'
    date = v['when'] or v['recorded']
    by = f", decided by {clean(v['by'])}" if v['by'] else ''
    adr = f" ({clean(v['adr'])})" if v['adr'] else ''
    if kind == 'Resolved':
        status = f'Resolved {date} (decision register{by}){adr}: {text}'
    else:
        status = f'Open. Approach agreed {date} (decision register{by}): {text}'
    outcome[did] = dict(kind=kind, text=text, status=status.replace('|', '/'), recorded=v['recorded'])


# ---- apply to the specifications ----
changed, seen = 0, set()
for ab in ABBR:
    p = os.path.join(SPECS, FOLDER[ab], '18-assumptions-decisions-gaps.md')
    lines = open(p).read().split('\n')
    for i, line in enumerate(lines):
        m = re.match(r'\| <a id="dec-[a-z]+-\d+"></a>(DEC-[A-Z]+-\d{3}) \|', line)
        if not m or m.group(1) not in outcome:
            continue
        did = m.group(1)
        seen.add(did)
        body = line.rstrip()
        assert body.endswith('|'), line
        head, _old = body[:-1].rstrip().rsplit(' | ', 1)
        new = f"{head} | {outcome[did]['status']} |"
        if new != line:
            lines[i] = new
            changed += 1
    # dated note under the 18.3 heading (replaced on each run)
    mine = [d for d in outcome if d.split('-')[1] == ab]
    n_res = sum(outcome[d]['kind'] == 'Resolved' for d in mine)
    date = max(outcome[d]['recorded'] for d in mine)
    note = (f"> **Decision register ({date}).** The decision outcomes recorded in the implementation plan "
            f"([outcomes.csv]({OUTCOMES_LINK})) were applied to this "
            f"table: {n_res} decisions are resolved and {len(mine) - n_res} {'stays' if len(mine) - n_res == 1 else 'stay'} open with an agreed approach, as the Status column shows. "
            "Where a requirement or other text in this specification still describes a resolved decision as open or as a working position, "
            "the Status here prevails. Selected technology is listed in the [technology stack](../../implementation_plan/decisions/technology-stack.md).")
    lines = [x for x in lines if not x.startswith('> **Decision register (')]
    k = next(i for i, x in enumerate(lines) if x.startswith('## 18.3'))
    if lines[k + 1] == '' and lines[k + 2] == '' :
        del lines[k + 1]
    lines[k + 1:k + 1] = ['', note]
    open(p, 'w').write('\n'.join(lines))
notfound = set(outcome) - seen
if notfound:
    sys.exit('Decisions not found in section 18.3: ' + ', '.join(sorted(notfound)))

# ---- Domain 2 technology policy: point to the selected stack ----
p = os.path.join(SPECS, 'D02-ISE', '14-architecture-constraints.md')
lines = [x for x in open(p).read().split('\n') if not x.startswith('> **Technology selected (')]
k = next(i for i, x in enumerate(lines) if x.startswith('## 14.4'))
TECH_DATE = max(t['recorded'] for t in tech)
lines[k + 1:k + 1] = ['', f"> **Technology selected ({TECH_DATE}).** The products for this platform have since been selected in the implementation plan's "
                      "decision register and are listed in the [technology stack](../../implementation_plan/decisions/technology-stack.md) "
                      "(DEC-ISE-003 and related decisions). The policy below still applies to every selected product."]
while lines[k + 3] == '' and lines[k + 4] == '':
    del lines[k + 3]
open(p, 'w').write('\n'.join(lines))

# ---- data/decision-register.csv ----
with open(os.path.join(PLAN, 'data', 'decision-register.csv'), 'w', newline='') as fh:
    w = csv.writer(fh)
    w.writerow(['sheet', 'row', 'decision_id', 'item', 'chosen_option', 'same_as_recommendation', 'outcome', 'recorded_status',
                'status', 'adr_reference', 'decided_by', 'date_decided', 'notes'])
    for t in tech:
        w.writerow(['Tech stack', t['no'], '; '.join(t['ids']), t['item'], t['chosen'], 'yes' if t['chosen'] == t['rec'] else 'no',
                    'Selected', '', t['status'], t['adr'] or '', t['by'] or '', t['when'] or '', t['notes'] or ''])
    for did, v in theme.items():
        o = outcome.get(did, dict(kind='', status=''))
        w.writerow([v['theme'], '', did, clean(v['scope']), v['chosen'], 'yes' if v['chosen'] == v['rec'] else 'no',
                    o['kind'], o['status'], v['status'], v['adr'] or '', v['by'] or '', v['when'] or '', v['notes'] or ''])

# ---- decisions/technology-stack.md ----
def DL(d):
    return f"[{d}](../../domain_specs/{FOLDER[d.split('-')[1]]}/18-assumptions-decisions-gaps.md#{d.lower()})"


n_changed = sum(t['chosen'] != t['rec'] for t in tech)


def record_state():
    n = len(tech)
    dec, by, adr = (sum(1 for t in tech if c(t)) for c in (lambda t: t['status'] == 'Decided', lambda t: t['by'], lambda t: t['adr']))
    if not (dec or by or adr):
        return ('The outcomes file does not yet record who decided, a decision date or an architecture decision record for any row, '
                'and every row\'s status is still "Open".')
    return f'Of the {n} rows, {dec} have status Decided, {by} record who decided and {adr} an architecture decision record.'


O = [GENERATED, '', '[Implementation plan](../README.md) / Technology stack', '', '# Technology Stack', '',
     f'The technology selected for the HIS, as recorded in [outcomes.csv](outcomes.csv) (rows TS-01 to TS-{len(tech):02d}) '
     f'on {TECH_DATE}. It has {len(tech)} selections; {len(tech) - n_changed} follow the '
     f'recommendation that was proposed for review and {n_changed} differ from it.', '',
     f'**Status.** Selected in the decision register. {record_state()} PRS section 28.1 and DEP-004 require each '
     'selection to be recorded as an architecture decision record and entered in the SBOM, and the Enterprise Architecture Board is '
     'the named owner of the technology decisions. Named products remain subject to the dependency rules in '
     '[section 3](#s3).', '',
     '<a id="s1"></a>', '', '## 1. Selected stack', '']
for g in dict.fromkeys(t['group'] for t in tech):
    O += [f'### {g}', '', '| No. | Item | Selected | Decision | Needed before | Note |', '|---|---|---|---|---|---|']
    for t in [x for x in tech if x['group'] == g]:
        note = t['notes'].replace('|', '/')
        if t['chosen'] != t['rec'] and not note:
            note = 'Differs from the recommendation.'
        need = f"Stage {int(t['stage'])}" + (f", [{t['slice']}](../delivery/slices/{t['slice'].split('-')[0]}.md#{t['slice'].lower()})" if t['slice'] else '')
        O.append(f"| {t['no']} | {cell(t['item'])} | {cell(t['chosen'])} | {', '.join(DL(i) for i in t['ids']) or 'Not recorded in the specifications'} | {need} | {note} |")
    O.append('')

O += ['<a id="s2"></a>', '', '## 2. Points to confirm', '',
      '| Row | Item | Point |', '|---|---|---|']
for t in tech:
    if t['notes'] and (t['status'] != 'Decided' or t['notes'].startswith('Condition:')):
        O.append(f"| {t['no']} | {cell(t['item'])} | {t['notes'].replace('|', '/')} |")
O += ['', '<a id="s3"></a>', '', '## 3. Rules every selection must still pass', '',
      'The PRS dependency rules apply to each named product at the time it is adopted:', '',
      '- **DEP-001**: no proprietary runtime, clinical database or integration engine for core workflows.',
      '- **DEP-003**: no unmaintained or abandoned open-source application as a mandatory dependency. Check the maintainer, release history and security disclosure process of each product when it is adopted.',
      '- **DEP-004**: every dependency in the SBOM with version, licence, origin and vulnerability status.',
      '- **DEP-005**: a supported replacement path for each dependency that could impair clinical operations.',
      '- **DEP-006**: no critical clinical workflow depends on a third-party cloud control plane or on internet access.',
      '- **DEP-008**: the hospital can build, deploy, patch and restore from its own repositories, keys and runbooks.', '',
      '<a id="s4"></a>', '', '## 4. Effect on the specification decisions', '',
      'These selections settle the following decisions in the specifications; their Status in section 18.3 now records the outcome.', '',
      '| Decision | Outcome |', '|---|---|']
for did in sorted({i for t in tech for i in t['ids']}, key=lambda d: (ABBR.index(d.split('-')[1]), d)):
    if did in outcome:
        O.append(f"| {DL(did)} | {outcome[did]['kind']}: {cell(outcome[did]['text'])} |")
O += ['', 'Data: [data/decision-register.csv](../data/decision-register.csv). All decisions: [decision-plan.md](decision-plan.md).', '']
open(os.path.join(PLAN, 'decisions', 'technology-stack.md'), 'w').write('\n'.join(O))

k = collections.Counter(o['kind'] for o in outcome.values())
print(f"decisions: {len(outcome)}  resolved: {k['Resolved']}  still open with agreed approach: {k['Open']}  "
      f"specification rows changed: {changed}  tech stack selections: {len(tech)} ({n_changed} differ from the recommendation)")
