#!/usr/bin/env python3
"""Build the decision plan from tools/definitions/decisions_def.py, data/decisions.csv and data/slices.csv.

Writes  decisions/decision-plan.md and data/decision-plan.csv   (under docs/implementation_plan)
Run:    python3 docs/implementation_plan/tools/build_decisions.py   (after extract.py and build_slices.py)
Fails if a decision is in no theme or in two themes, or a theme names an unknown decision.
Resolved decisions stay in their theme and are shown as resolved; a theme whose decisions are all resolved is settled.
"""
import os, sys, csv, collections

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, 'definitions'))
sys.dont_write_bytecode = True
from decisions_def import THEMES, ANCHORS  # noqa: E402
from slices_def import PHASES, SLICES as SLICE_DEFS  # noqa: E402

PLAN = os.path.dirname(HERE)
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_decisions.py from tools/definitions/decisions_def.py and data/decisions.csv. Edit decisions_def.py, not this file. -->'
ORDER = [s['id'] for s in SLICE_DEFS]
FLOW = {s['id']: s['id'].split('-')[0] for s in SLICE_DEFS}
TITLE = {s['id']: s['title'] for s in SLICE_DEFS}

DEC = {r['decision_id']: r for r in csv.DictReader(open(os.path.join(PLAN, 'data', 'decisions.csv')))}
SL, first_stage = {}, {}
for r in csv.DictReader(open(os.path.join(PLAN, 'data', 'slices.csv'))):
    SL[r['requirement_id']] = (r['slice'], int(r['phase']))
    first_stage[r['domain']] = min(first_stage.get(r['domain'], 9), int(r['phase']))

errors, theme_of, resolved_in = [], {}, {}
for t in THEMES:
    t['decs'], t['resolved'] = [], []
    for x in [i.strip() for i in t['ids'].split(',')]:
        d = 'DEC-' + x
        if d not in DEC:
            errors.append(f'{t["id"]}: unknown decision {d}')
        elif d in theme_of or d in resolved_in:
            errors.append(f'{d} is in both {theme_of.get(d) or resolved_in[d]} and {t["id"]}')
        elif DEC[d]['class'] == 'R':
            resolved_in[d] = t['id']
            t['resolved'].append(d)
        else:
            theme_of[d] = t['id']
            t['decs'].append(d)
errors += [f'open decision {d} is in no theme: {DEC[d]["decision_required"][:80]}' for d in DEC if DEC[d]['class'] != 'R' and d not in theme_of]
errors += [f'anchor {a} is not a decision in any theme' for a in ANCHORS if a not in theme_of and a not in resolved_in]
if errors:
    print('\n'.join(errors))
    sys.exit(1)

for d, r in DEC.items():
    ab = r['domain']
    cited = sorted({SL[f] for f in r['all_requirements'].split()}, key=lambda x: (x[1], ORDER.index(x[0])))
    r['slices'] = [s for s, _ in cited]
    r['stage'] = cited[0][1] if cited else None
    r['first_slice'] = cited[0][0] if cited else None
    r['n_must'] = len(r['must_requirements'].split())
    r['reach'] = 'No requirement cites it' if not cited else ('Wide' if len(cited) >= 2 or r['n_must'] >= 4 else 'One slice')
for t in THEMES:
    cited_stages = [DEC[d]['stage'] for d in t['decs'] if DEC[d]['stage']]
    for d in t['decs']:   # a decision no requirement cites takes the stage of its theme
        if not DEC[d]['stage']:
            DEC[d]['stage'] = min(cited_stages) if cited_stages else first_stage[DEC[d]['domain']]
    t['decs'].sort(key=lambda d: (d not in ANCHORS, DEC[d]['stage'], d))
    t['stage'] = min([DEC[d]['stage'] for d in t['decs']], default=None)
    t['anchors'] = [d for d in t['decs'] if d in ANCHORS]
OPEN_THEMES = [t for t in THEMES if t['decs']]
SETTLED = [t for t in THEMES if not t['decs']]
OPEN_ANCHORS = [a for a in ANCHORS if a in theme_of]
n_res = len(resolved_in)


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


def SLK(s):
    return f'[{s}](../delivery/slices/{FLOW[s]}.md#{s.lower()})'


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


def TLK(t):
    return f'[{t["id"]}](#{t["id"].lower()}) {t["title"]}'


n_open = len(theme_of)
by_stage = collections.Counter(DEC[d]['stage'] for d in theme_of)
RANK = {'No': 0, 'Partly': 1, 'Yes': 2}
O = [GENERATED, '', '[Implementation plan](../README.md) / Decision plan', '', '# Decision Plan', '',
     f'The domain specifications record {n_open + n_res} decisions in {len(THEMES)} themes. {n_res} are resolved and {n_open} are still open, '
     f'in {len(OPEN_THEMES)} themes; {len(SETTLED)} themes are fully settled. For each theme with open decisions this plan states: who should drive it, '
     'the stage it must be settled before, and what it costs to carry on with the working position if the decision later goes the other way. '
     'The ranked list of individual decisions is in [blocking decisions](blocking-decisions.md); this page is the plan for closing them.', '',
     '## 1. How to read this plan', '',
     '- **Working position.** Every specification states the position it assumed for each open decision so that requirements could be written. Building on it is possible; the risk is rework if the decision differs.',
     '- **Settle before.** The stage whose slices first build on the decision. Derived from the plan: the earliest [slice](../delivery/slices.md) containing a requirement that cites the decision, or, where no requirement cites it, the earliest such stage among the other decisions of its theme. '
     'A decision is needed when build of that slice starts and at the latest before its gate is signed.',
     '- **Can build start on the working position?** *No*: there is nothing to build on until the decision is made. *Partly*: the mechanism can be built but its content or a key choice cannot be assumed. *Yes*: build can proceed and change later.',
     '- **Cost of proceeding.** A judgement, per theme, of what would have to be redone: *High* reaches stored data, several domains or passed gates; *Medium* is rework of contracts or one domain\'s behaviour; *Low* is contained configuration or scope.',
     '- **Lead.** One role proposed to drive the theme. The specifications name owners per decision, often several; those are shown against each decision.',
     '- **Anchor decisions** carry most of a theme\'s cost and should be settled first.',
     '- **Reach** of a decision is derived: *Wide* if requirements in two or more slices, or four or more Must requirements, cite it; *One slice*; or *No requirement cites it*.', '',
     '## 2. Summary', '',
     '| Theme | Lead | Settle before | Can build start on the working position? | Cost of proceeding | Open | Resolved | Open anchor decisions |', '|---|---|---|---|---|---|---|---|']
for t in sorted(OPEN_THEMES, key=lambda t: (t['stage'], RANK[t['proceed']], t['id'])):
    O.append(f'| {TLK(t)} | {t["lead"]} | Stage {t["stage"]} | {t["proceed"]} | {t["cost"]} | {len(t["decs"])} | {len(t["resolved"])} | {", ".join(DL(d) for d in t["anchors"]) or "–"} |')
for t in SETTLED:
    O.append(f'| {TLK(t)} | {t["lead"]} | Settled | – | – | 0 | {len(t["resolved"])} | – |')
O += ['', f'Open decisions by the stage they must be settled before: ' + ', '.join(f'stage {s}: {by_stage[s]}' for s in sorted(by_stage)) + '.', '',
      '## 3. What to settle first', '']
no = [t for t in OPEN_THEMES if t['proceed'] == 'No']
O += ['**Before any build (phase 0).** These themes have no working position to build on, or their anchor decision is written into data from the first transaction:', '']
O += [f'- {TLK(t)}: ' + ('; '.join(f'{DL(d)} ({ANCHORS[d][0].lower() + ANCHORS[d][1:].rstrip(".")})' for d in t['anchors']) or 'its anchor decisions are resolved; ' + str(len(t['decs'])) + ' other decisions remain') + '.' for t in no] or ['- None: every such theme is settled.']
O += ['', '**Anchor decisions by stage.** The other anchors, in the order their stage arrives:', '',
      '| Settle before | Decision | Theme | Why it anchors the theme | Owner named in the specification | First slice that needs it |', '|---|---|---|---|---|---|']
rest = sorted([d for d in OPEN_ANCHORS if theme_of[d] not in {t['id'] for t in no}], key=lambda d: (DEC[d]['stage'], d))
tb = {t['id']: t for t in THEMES}
for d in rest:
    r = DEC[d]
    O.append(f'| Stage {r["stage"]} | {DL(d)} {td(r["decision_required"])} | [{theme_of[d]}](#{theme_of[d].lower()}) | {ANCHORS[d]} | {td(r["owner"])} | {SLK(r["first_slice"]) if r["first_slice"] else "–"} |')
O += ['', '**Lead time.** Three themes depend on parties outside the project and should start early regardless of their stage: terminology licensing ([T03](#t03)), national interoperability and certification requirements ([T07](#t07)) and payer onboarding ([T15](#t15)).', '',
      '## 4. Themes', '']
for t in THEMES:
    O += [f'<a id="{t["id"].lower()}"></a>', '', f'### {t["id"]} {t["title"]}', '',
          '| Attribute | Value |', '|---|---|',
          f'| Lead | {t["lead"]} |',
          f'| Settle before | ' + (f'Stage {t["stage"]} ({PHASES[t["stage"]]}); individual decisions as listed below' if t['decs'] else 'Settled: every decision in this theme is resolved') + ' |',
          f'| Can build start on the working position? | {t["proceed"] if t["decs"] else "–"} |',
          f'| Cost of proceeding | {t["cost"] if t["decs"] else "–"} |',
          f'| Decisions | {len(t["decs"])} open, {len(t["resolved"])} resolved |', '']
    if t['resolved']:
        O += [f'**Position before the decisions of this theme were taken.** {t["position"]}', '']
    else:
        O += [f'**Working position.** {t["position"]}', '']
    if t['decs']:
        O += [f'**Cost of proceeding on it.** {t["cost_text"]}', '']
        if t['resolved']:
            O += ['The two paragraphs above were written before any decision in this theme was taken; the resolved decisions below take precedence over them.', '']
    if t['anchors']:
        O += ['**Settle first.** ' + ' '.join(f'{DL(d)}: {ANCHORS[d]}' for d in t['anchors']), '']
    if t['decs']:
        O += ['| Open decision | Decision required | Owner named in the specification | Settle before | First slice that needs it | Must requirements citing it | Reach | Status |', '|---|---|---|---|---|---|---|---|']
        for d in t['decs']:
            r = DEC[d]
            O.append(f'| {"**" + DL(d) + "**" if d in ANCHORS else DL(d)} | {td(r["decision_required"])} | {td(r["owner"])} | Stage {r["stage"]} | '
                     f'{SLK(r["first_slice"]) if r["first_slice"] else "–"} | {r["n_must"]} | {r["reach"]} | {td(r["status"])} |')
        O.append('')
    if t['resolved']:
        O += ['| Resolved decision | Decision required | Resolution |', '|---|---|---|']
        for d in t['resolved']:
            O.append(f'| {"**" + DL(d) + "**" if d in ANCHORS else DL(d)} | {td(DEC[d]["decision_required"])} | {td(DEC[d]["status"])} |')
        O.append('')
res = [d for d in DEC if DEC[d]['class'] == 'R' and d not in resolved_in]
O += ['## 5. Decisions resolved before the themes were formed', '', 'Decisions resolved within a theme are listed under that theme in section 4.', '', '| Decision | Resolution |', '|---|---|']
O += [f'| {DL(d)} {td(DEC[d]["decision_required"])} | {td(DEC[d]["status"])} |' for d in res] or ['| – | – |']
O += ['', '## 6. Recording a decision', '',
      'When a decision is made, record it in [outcomes.csv](outcomes.csv): the status, the outcome, who decided, the date, and `settled` set to `yes`. '
      'Then run `tools/build.py`. The build writes the outcome into the Status column of section 18.3 of the owning specification, '
      'and regenerates the plan pages. Update by hand any requirement that assumed otherwise. A resolved decision moves to the resolved list of its theme and drops out of the slice pages automatically. If the outcome differs from the working position, review the slices listed against the decision before their gates.', '',
      '## 7. Limits', '',
      '- **Themes, leads and cost ratings are judgements** made from the decision texts, written in [tools/definitions/decisions_def.py](../tools/definitions/decisions_def.py). The owners should confirm them.',
      '- **"Settle before" follows citations.** A decision that affects a slice whose requirements do not cite it will show a later stage than it should; the theme text notes the known cases.',
      '- **Cost is qualitative.** No effort or duration is estimated.',
      '- **Known gaps are not in this plan.** The specifications also list missing values (thresholds, retention periods, targets) in section 18.4; many must be supplied before a gate can be signed and are best handled alongside the theme they belong to.',
      '', 'Data: [data/decision-plan.csv](../data/decision-plan.csv).']
open(os.path.join(PLAN, 'decisions', 'decision-plan.md'), 'w').write('\n'.join(O) + '\n')
with open(os.path.join(PLAN, 'data', 'decision-plan.csv'), 'w', newline='') as fh:
    w = csv.writer(fh)
    w.writerow(['decision_id', 'theme', 'theme_title', 'theme_lead', 'anchor', 'settle_before_stage', 'first_slice', 'slices', 'must_requirements_citing',
                'reach', 'theme_can_proceed', 'theme_cost', 'owner_in_specification', 'decision_required'])
    for t in THEMES:
        for d in t['decs']:
            r = DEC[d]
            w.writerow([d, t['id'], t['title'], t['lead'], 'yes' if d in ANCHORS else '', r['stage'], r['first_slice'] or '', ' '.join(r['slices']), r['n_must'],
                        r['reach'], t['proceed'], t['cost'], r['owner'], r['decision_required']])
print('themes', len(THEMES), 'settled', len(SETTLED), 'resolved', n_res, 'open decisions', n_open, 'anchors', len(ANCHORS), 'by stage', dict(sorted(by_stage.items())))
for t in THEMES:
    print(f'  {t["id"]} stage {t["stage"]} {t["proceed"]:6} {t["cost"]:6} open={len(t["decs"]):2} resolved={len(t["resolved"]):2} {t["title"]}')
