#!/usr/bin/env python3
"""Build the consumer side of every event contract from the publishers' event tables.

Reads   docs/domain_specs/*/08-integration.md     section 8.5, the published-event table of each domain
Writes  docs/domain_specs/*/08-integration.md     an "Events consumed" block at the end of section 8.5
        delivery/event-catalogue.md               every event with its producer and consumers, and the checks below

The publisher's Consumers column is the single record of who consumes an event. A consumer's "Events consumed"
table is generated from it, so the two sides cannot disagree. To add or remove a consumer, change the publisher's
row and rebuild.

Reading the Consumers column:
  "3, 4, 8", "Domains 3 and 8", "[Domain 7](...)"     those domains
  "All domains", "record-holding domains"             every domain except the producer
  "Owning domain", "Requesting domain", ...          every domain, with the condition shown in the Condition column;
                                                     "Owning domains (1, 3, 4, 5)" or "(3 or 4)" names them
  "Same as EVT-XXX-NNN"                               the consumers of that event
  modules of the producer and named roles (operations, stewards, ...) are not domains and are left out

Checks (the build fails on the first; the others are listed on the catalogue page):
  1. an event name is published by two domains
  2. an event name is not a PascalCase past fact
  3. a domain links to another domain's event that does not list it as a consumer

Run:    python3 docs/implementation_plan/tools/build.py   (runs this script)
"""
import os, re, sys, glob, collections

HERE = os.path.dirname(os.path.abspath(__file__))
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 = {i + 1: f'D{i + 1:02d}-{a}' for i, a in enumerate(ABBR)}
NUM = {a: i + 1 for i, a in enumerate(ABBR)}
ALL = set(FOLDER)
START = '<!-- consumed-events:start. Generated by implementation_plan/tools/build_events.py from the publishers\' event tables. Edit those, not this block. -->'
END = '<!-- consumed-events:end -->'
ROW = re.compile(r'^\| <a id="(evt-[a-z]+-\d+)"></a>(EVT-([A-Z]+)-\d+) \| (.*?) \| (.*?) \| (.*?) \| (.*?) \|\s*$', re.M)
CONTEXT = re.compile(r'\b(owning|requesting|reporting) domains?\b', re.I)


def plain(t):
    return re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', t).replace('`', '').strip()


def path08(n):
    return os.path.join(SPECS, FOLDER[n], '08-integration.md')


def strip_block(t):
    i, j = t.find(START), t.find(END)
    if i >= 0 and j > i:
        t = t[:i].rstrip('\n') + '\n\n' + t[j + len(END):].lstrip('\n')
    return t


# ---- read the publishers ----
events = []
for n in FOLDER:
    t = strip_block(open(path08(n), encoding='utf-8').read())
    for anchor, eid, ab, name, prod, cons, trig in ROW.findall(t):
        name = plain(name)
        events.append(dict(id=eid, anchor=anchor, dom=n, name=name, prod=plain(prod), raw=plain(cons),
                           trig=plain(trig), retired=name.lower().startswith('retired')))
BYID = {e['id']: e for e in events}


def resolve(e, seen=()):
    """Return {domain: condition} for an event's Consumers column."""
    raw, out = e['raw'], {}
    m = re.search(r'Same as (EVT-[A-Z]+-\d+)', raw)
    if m and m.group(1) in BYID and m.group(1) not in seen:
        return resolve(BYID[m.group(1)], seen + (e['id'],))
    for seg in re.split(r';|,(?![^()]*\))', raw):
        seg = seg.strip()
        if not seg or seg in ('–', '-'):
            continue
        if re.search(r'\b(all|record-holding) domains\b', seg, re.I):
            for d in ALL:
                out.setdefault(d, '')
            continue
        ctx = CONTEXT.search(seg)
        if ctx:
            named = re.findall(r'\b(\d{1,2})\b', seg)
            if named:
                for x in named:
                    out.setdefault(int(x), '')
            else:
                for d in ALL:
                    out.setdefault(d, f'When this domain is the {ctx.group(1).lower()} domain')
            continue
        if re.match(r'^MOD-', seg):
            continue
        nums = re.findall(r'(?:^|Domains?\s+|,\s*|and\s+)(\d{1,2})\b', seg)
        for x in nums:
            if 1 <= int(x) <= 10:
                out.setdefault(int(x), '')
    for k in [k for k in out if not 1 <= k <= 10]:
        del out[k]
    out.pop(e['dom'], None)
    return out


for e in events:
    e['cons'] = {} if e['retired'] else resolve(e)


def link(e, frm):
    return f"[{e['id']}](../{FOLDER[e['dom']]}/08-integration.md#{e['anchor']})" if frm != e['dom'] else f"[{e['id']}](#{e['anchor']})"


# ---- write the consumer blocks ----
for n in FOLDER:
    p = path08(n)
    t = strip_block(open(p, encoding='utf-8').read())
    rows = [e for e in events if n in e['cons']]
    B = [START, '', '<a id="s8-5-consumed"></a>', '', '### Events consumed', '',
         'The events this domain consumes, as listed in each publisher\'s section 8.5. The publisher\'s table is the single '
         'record of who consumes an event: to add or remove a consumer, change the publisher\'s Consumers column and rebuild.', '']
    if rows:
        B += ['| Event | Name | Producer | Producer\'s trigger | Condition |', '|---|---|---|---|---|']
        for e in rows:
            B.append(f"| {link(e, n)} | {e['name'].replace('|', '/')} | [{FOLDER[e['dom']]}](../{FOLDER[e['dom']]}/README.md) | "
                     f"{e['trig'].replace('|', '/')} | {e['cons'][n] or '–'} |")
    else:
        B.append('No other domain lists this domain as a consumer.')
    B += ['', END]
    marker = '<a id="s8-6"></a>'
    if t.count(marker) != 1:
        sys.exit(f'{p}: expected one {marker}')
    t = t.replace(marker, '\n'.join(B) + '\n\n' + marker)
    open(p, 'w', encoding='utf-8').write(t)

# ---- checks ----
owners = collections.defaultdict(set)
bad_names = []
for e in events:
    if e['retired']:
        continue
    for nm in re.split(r'\s*/\s*', re.sub(r'\(.*?\)', '', e['name'])):
        nm = nm.strip()
        if not nm:
            continue
        owners[nm].add(e['id'])
        if not re.fullmatch(r'[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+', nm):
            bad_names.append((e, nm))
dupes = {nm: ids for nm, ids in owners.items() if len({BYID[i]['dom'] for i in ids}) > 1}

unlisted = []
ref = re.compile(r'\]\(\.\./(?:\.\./)?(D\d\d-([A-Z]+))/08-integration\.md#(evt-[a-z]+-\d+)\)')
for n in FOLDER:
    for f in glob.glob(os.path.join(SPECS, FOLDER[n], '**', '*.md'), recursive=True):
        if f.endswith('ID-INDEX.md'):
            continue
        txt = strip_block(open(f, encoding='utf-8').read())
        for folder, ab, anchor in set(ref.findall(txt)):
            e = next((x for x in events if x['anchor'] == anchor), None)
            if e and e['dom'] != n and not e['retired'] and n not in e['cons']:
                unlisted.append((n, os.path.relpath(f, SPECS), e))

# ---- catalogue page ----
pairs = sum(len(e['cons']) for e in events)
O = ['<!-- Generated by tools/build_events.py from section 8.5 of the specifications. Edit those, not this file. -->', '',
     '[Implementation plan](../README.md) / Event catalogue', '', '# Event Catalogue', '',
     f'{sum(not e["retired"] for e in events)} published events and {pairs} producer-to-consumer pairs, read from section 8.5 of each '
     'specification. The publisher\'s Consumers column is the single record of who consumes an event; each specification\'s '
     '"Events consumed" table is generated from it. The naming convention and the envelope are in '
     '[system architecture section 6.3](../../architecture/system-architecture.md#s6-3).', '',
     '## Checks', '',
     f'- Event names published by more than one domain: **{len(dupes)}**' + (' (the build fails on any)' if not dupes else ''),
     f'- Event names that are not a PascalCase past fact: **{len(bad_names)}**',
     f'- Links to another domain\'s event from a domain that event does not list as a consumer: **{len(unlisted)}**', '']
if dupes:
    O += ['### Duplicate names', '', '| Name | Events |', '|---|---|'] + [f'| {nm} | {", ".join(sorted(ids))} |' for nm, ids in sorted(dupes.items())] + ['']
if bad_names:
    O += ['### Names outside the convention', '', '| Event | Name |', '|---|---|'] + \
         [f"| [{e['id']}](../../domain_specs/{FOLDER[e['dom']]}/08-integration.md#{e['anchor']}) | {nm} |" for e, nm in bad_names] + ['']
if unlisted:
    O += ['### Consumers not listed by the publisher', '',
          'Either add the domain to the publisher\'s Consumers column, or the reference is documentary and can stay.', '',
          '| Domain | File | Event | Publisher\'s consumers |', '|---|---|---|---|']
    for n, f, e in sorted(unlisted, key=lambda x: (x[0], x[2]['id'])):
        O.append(f"| {FOLDER[n]} | [{f}](../../domain_specs/{f}) | [{e['id']}](../../domain_specs/{FOLDER[e['dom']]}/08-integration.md#{e['anchor']}) {e['name']} | {e['raw']} |")
    O.append('')
O += ['## Events', '', '| Event | Name | Producer | Consumers | Trigger |', '|---|---|---|---|---|']
for e in events:
    cons = 'Retired' if e['retired'] else ', '.join(
        FOLDER[d] + (' (conditional)' if e['cons'][d] else '') for d in sorted(e['cons'])) or 'No domain (operational roles only)'
    O.append(f"| [{e['id']}](../../domain_specs/{FOLDER[e['dom']]}/08-integration.md#{e['anchor']}) | {e['name'].replace('|', '/')} | "
             f"{FOLDER[e['dom']]} | {cons} | {e['trig'].replace('|', '/')} |")
os.makedirs(os.path.join(PLAN, 'delivery'), exist_ok=True)
open(os.path.join(PLAN, 'delivery', 'event-catalogue.md'), 'w', encoding='utf-8').write('\n'.join(O) + '\n')

print(f'events {len(events)}  consumer pairs {pairs}  duplicate names {len(dupes)}  off-convention names {len(bad_names)}  '
      f'unlisted consumers {len(unlisted)}')
if dupes:
    sys.exit('duplicate event names: ' + '; '.join(f'{k}: {", ".join(sorted(v))}' for k, v in dupes.items()))
