#!/usr/bin/env python3
"""Write the architecture decision records of the technology selections, and the index of all decision records.

Reads   decisions/outcomes.csv (rows TS-01 to TS-32), tools/definitions/tech_stack.csv,
        docs/architecture/decisions/ADR-HIS-*.md (the hand-written records, for the index)
Writes  docs/architecture/decisions/ADR-HIS-001.md to ADR-HIS-032.md (one per technology stack row) and
        docs/architecture/decisions/README.md (the index)
Run:    python3 docs/implementation_plan/tools/build_adrs.py   (after apply_decisions.py)

Records ADR-HIS-033 and later are hand-written and never overwritten. A generated record states only what the
register and the technology stack sheet hold; to change one, edit those and rebuild.
"""
import csv, glob, os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))
PLAN = os.path.dirname(HERE)
DOCS = os.path.dirname(PLAN)
OUT = os.path.join(DOCS, 'architecture', 'decisions')
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 implementation_plan/tools/build_adrs.py from decisions/outcomes.csv and '
             'tools/definitions/tech_stack.csv. Edit those, not this file. -->')
RECORD_DRAFTED = '2026-11-24'
RECORD_APPROVED = '2026-11-24'   # the Enterprise Architecture Board approved ADR-HIS-001 to ADR-HIS-039 (PR #8, FN-S01)
TS_COUNT = 32


def adr_id(n):
    return f'ADR-HIS-{n:03d}'


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


def owner(s):
    return s.replace(' (proposed)', '').replace('Enterprise architecture board', 'Enterprise Architecture Board')


def sentence(s):
    s = s.strip()
    return s if not s or s[-1] in '.!?' else s + '.'


outcomes = {r['id']: r for r in csv.DictReader(open(os.path.join(PLAN, 'decisions', 'outcomes.csv')))}
rows = list(csv.DictReader(open(os.path.join(HERE, 'definitions', 'tech_stack.csv'))))
if len(rows) != TS_COUNT:
    sys.exit(f'build_adrs.py: expected {TS_COUNT} technology stack rows, found {len(rows)}')
os.makedirs(OUT, exist_ok=True)

for r in rows:
    n = int(r['no'])
    o = outcomes[f'TS-{n:02d}']
    if o['status'] != 'Decided':
        status, decided = 'Proposed', 'Not yet decided'
    else:
        status, decided = 'Accepted', f"{o['date_decided']} by {o['decided_by'] or owner(r['owner'])}"
    decs = list(dict.fromkeys(re.findall(r'DEC-[A-Z]{3}-\d{3}', r['decision_ids'])))
    notes = o['notes'].strip()
    condition = notes[len('Condition:'):].strip() if notes.startswith('Condition:') else ''
    other_notes = '' if condition else notes
    chosen, rec = o['chosen_option'].strip(), r['recommendation'].strip()
    need = f"Stage {int(r['needed_before_stage'])}" + (f", slice {r['first_slice']}" if r['first_slice'] else '')
    out = [GENERATED, '', f'[Architecture](../system-architecture.md) / [Decision records](README.md) / {adr_id(n)}', '',
           f'# {adr_id(n)} {r["item"]}', '',
           '| | |', '|---|---|',
           f'| Status | {status} |',
           f'| Decided | {decided} |',
           f'| Record | Drafted {RECORD_DRAFTED}; approved {RECORD_APPROVED} by the Enterprise Architecture Board |',
           f'| Technology stack row | {n}, group "{r["group"]}" ([technology stack](../../implementation_plan/decisions/technology-stack.md#s1)) |',
           f'| Settles | {", ".join(dec_link(d) for d in decs) if decs else "No specification decision; a technology selection only"} |',
           f'| Needed before | {need} |', '',
           '## Context', '', sentence(r['scope'])]
    if r['specification_recommendation'].strip():
        out += ['', 'The specifications recommended: ' + sentence(r['specification_recommendation'])]
    if r['constraints'].strip():
        out += ['', 'Constraint from the specifications: ' + sentence(r['constraints'])]
    out += ['', '## Options considered', '']
    out += [f'- {x.strip()}' for x in r['options'].split(';') if x.strip()]
    out += ['', '## Decision', '', sentence(chosen), '', '## Rationale', '']
    if chosen == rec:
        out.append('Follows the recommendation prepared for review on 15 November 2026, which reads as the decision above.')
    else:
        out.append('Differs from the recommendation prepared for review on 15 November 2026: "' + rec.rstrip('.') + '."')
        if other_notes:
            out += ['', sentence(other_notes)]
    out += ['', '## Consequences', '',
            '- The product must pass the PRS dependency rules when adopted (DEP-001, DEP-003, DEP-004, DEP-005, DEP-006, DEP-008; '
            '[technology stack, section 3](../../implementation_plan/decisions/technology-stack.md#s3)).',
            '- It is entered in the software bill of materials, with version, licence, origin and vulnerability status, by the pipeline of foundation session FN-S05.']
    if condition:
        out.append('- **Condition:** ' + sentence(condition))
    if other_notes and chosen == rec:
        out += ['', '## Notes', '', sentence(other_notes)]
    open(os.path.join(OUT, f'{adr_id(n)}.md'), 'w').write('\n'.join(out) + '\n')

# ------------------------------------------------------------------ index of all records
entries = []
for p in sorted(glob.glob(os.path.join(OUT, 'ADR-HIS-*.md'))):
    t = open(p).read()
    title = re.search(r'^# (ADR-HIS-\d{3}) (.+)$', t, re.M)
    stat = re.search(r'^\| Status \| (.+?) \|$', t, re.M)
    dec = re.search(r'^\| Decided \| (.+?) \|$', t, re.M)
    rec = re.search(r'^\| Record \| (.+?) \|$', t, re.M)
    if not (title and stat and dec and rec):
        sys.exit(f'build_adrs.py: {os.path.basename(p)} lacks a title, Status, Decided or Record line')
    n = int(title.group(1)[-3:])
    entries.append((n, title.group(1), title.group(2), stat.group(1), dec.group(1), rec.group(1),
                    'Technology selection' if n <= TS_COUNT else 'Architecture', os.path.basename(p)))
idx = ['<!-- Generated by implementation_plan/tools/build_adrs.py. ADR-HIS-001 to ADR-HIS-032 are generated; '
       'later records are hand-written. Do not edit this index by hand. -->', '',
       '[Architecture](../system-architecture.md) / Decision records', '', '# Architecture Decision Records', '',
       f'The architecture decision records of the HIS, as PRS section 28.1 and DEP-004 require: one for each of the {TS_COUNT} technology selections '
       f'(ADR-HIS-001 to ADR-HIS-{TS_COUNT:03d}, generated from the decision register) and one for each architecture decision taken since '
       f'(ADR-HIS-{TS_COUNT + 1:03d} onward, written by hand). There are {len(entries)} records.', '',
       f'The records were drafted on {RECORD_DRAFTED}. The Enterprise Architecture Board, the named owner of the technology decisions, approved ADR-HIS-001 to '
       f'ADR-HIS-039 on {RECORD_APPROVED}, in the review of the FN-S01 pull request. A later record shows in its "Record" line whether it is approved yet.', '',
       '| Record | Title | Kind | Status | Decided | Record approval |', '|---|---|---|---|---|---|']
for n, i, title, stat, dec, rec, kind, fn in entries:
    idx.append(f'| [{i}]({fn}) | {title} | {kind} | {stat} | {dec} | {rec} |')
idx += ['', '**Adding a record.** A new architecture decision gets the next number as a hand-written file in this folder, with the same '
        'Status, Decided and Record lines; the build lists it here. A new technology selection is a new row of the technology stack sheet.', '']
open(os.path.join(OUT, 'README.md'), 'w').write('\n'.join(idx))
print(f'decision records: {len(entries)} ({sum(1 for e in entries if e[0] <= TS_COUNT)} generated)')
