#!/usr/bin/env python3
"""Keep the GitHub issues of the sessions in step with the session plan, and the plan in step with the issues.

The plan says what each session is and what it comes after; GitHub says where each session stands.

  sync_github.py setup [--project-title T]   once: create the labels and, with --project-title, the project board
  sync_github.py sync [--dry-run] [--all] [--commit]

`sync` does, in order:
  1. reads every issue and pull request of the repository;
  2. writes delivery/session-fixes.csv from the fix issues gate evidence sessions filed, and
     delivery/session-status.csv from the state of the session issues, then runs the plan build;
  3. creates the issues of every slice that has a session able to start (all slices with --all), with labels,
     milestone and "blocked by" links, and updates issues whose card data changed;
  4. sets the label `ready` on each issue whose predecessors are all closed, and the "Session status" field of the
     project board, if delivery/github.json names a project;
  5. with --commit, commits and pushes the files of step 2 when they changed.

A session issue is recognised by its title, which starts with the session identifier. The status of a session:
  Done        the issue is closed (a pull request with "Closes #n" was merged)
  Blocked     the issue carries the label `blocked` (the session stopped with a question)
  In review   a pull request from branch session/<SESSION-ID> is open
  Paused      the issue carries the label `paused` (set by launch_sessions.py pause)
  Running     the issue carries the label `running` (set by launch_sessions.py)
  Ready       every session it comes after is Done, and it carries no label `hold`
  Waiting     otherwise

Uses the GitHub CLI (`gh`), signed in with the `repo` and `project` scopes, or GH_TOKEN in a workflow.
Reads   data/sessions.csv, definitions/slices_def.py, delivery/github.json
Writes  delivery/session-status.csv, delivery/session-fixes.csv and, through the plan build, the generated plan
"""
import argparse, csv, json, os, re, subprocess, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))
PLAN = os.path.dirname(HERE)
STATUS_CSV = os.path.join(PLAN, 'delivery', 'session-status.csv')
FIXES_CSV = os.path.join(PLAN, 'delivery', 'session-fixes.csv')
CONFIG = os.path.join(PLAN, 'delivery', 'github.json')
GH = os.environ.get('HIS_GH', 'gh')
STATUS_FIELD = 'Session status'
STATUSES = ['Waiting', 'Ready', 'Running', 'Paused', 'In review', 'Blocked', 'Done']
FIX_RE = re.compile(r'^(.+-S\d{2})-F(\d+)$')
ID_RE = re.compile(r'^([A-Z]{2}(?:-\d+)?-S\d{2}(?:-[GF]\d+)?)\s')
LABELS = {   # name -> (colour, description)
    'ready': ('0e8a16', 'Every session it comes after is done; the launcher can start it'),
    'running': ('1d76db', 'An agent is working on it'),
    'paused': ('c2e0c6', 'A person paused the session; launch_sessions.py resume continues it'),
    'blocked': ('b60205', 'The session stopped and needs a person; remove the label when settled'),
    'hold': ('fbca04', 'Do not start this session yet'),
    'needs-person': ('d93f0b', 'The card has a "Needs a person" line'),
    'safety-review': ('5319e7', 'The card has a safety duty: a named safety review before merge'),
}
KIND_COLOUR, FLOW_COLOUR = 'c5def5', 'bfdadc'
DRY = False


def gh(*args, data=None, check=True):
    r = subprocess.run([GH] + list(args), input=data, capture_output=True, text=True)
    if check and r.returncode:
        sys.exit(f'gh {" ".join(args)} failed:\n{r.stderr.strip() or r.stdout.strip()}')
    return r


def many(text):
    """Parse the output of `gh api --paginate`: one JSON value after another; arrays are joined."""
    out, dec, i = [], json.JSONDecoder(), 0
    while i < len(text):
        if text[i].isspace():
            i += 1
            continue
        v, i = dec.raw_decode(text, i)
        out += v if isinstance(v, list) else [v]
    return out


def get(path):
    return many(gh('api', '--paginate', path).stdout)


def send(method, path, body=None, check=True):
    """A call that changes GitHub. In a dry run it is printed, not made."""
    if DRY:
        print(f'  would {method} {path} {json.dumps(body)[:160] if body else ""}')
        return None
    r = gh('api', '-X', method, path, '--input', '-', data=json.dumps(body or {}), check=check)
    if r.returncode:
        return None
    return json.loads(r.stdout) if r.stdout.strip() else {}


def repo_slug():
    url = subprocess.run(['git', '-C', HERE, 'remote', 'get-url', 'origin'], capture_output=True, text=True).stdout.strip()
    m = re.search(r'github\.com[:/](.+?)(?:\.git)?$', url)
    if not m:
        sys.exit(f'sync_github.py: origin ({url}) is not a GitHub repository')
    return m.group(1)


def config():
    return json.load(open(CONFIG)) if os.path.isfile(CONFIG) else {}


def kind_label(kind):
    return 'kind:' + kind.lower().replace(' ', '-')


def sid_of(title):
    m = ID_RE.match(title + ' ')
    return m.group(1) if m else None


def load_sessions():
    return list(csv.DictReader(open(os.path.join(PLAN, 'data', 'sessions.csv'))))


def fetch(repo):
    """Issues by session identifier, and the pull requests of each session branch."""
    issues, prs = {}, {}
    for i in get(f'repos/{repo}/issues?state=all&per_page=100'):
        if 'pull_request' in i:
            continue
        sid = sid_of(i['title'])
        if sid and i.get('state_reason') != 'not_planned':
            if sid in issues:
                print(f'  warning: issues #{issues[sid]["number"]} and #{i["number"]} both name {sid}; using the lower number')
            if sid not in issues or i['number'] < issues[sid]['number']:
                issues[sid] = i
    for p in get(f'repos/{repo}/pulls?state=all&per_page=100'):
        ref = p['head']['ref']
        if ref.startswith('session/'):
            prs.setdefault(ref[len('session/'):], []).append(p)
    return issues, prs


def labels_of(issue):
    return {x['name'] for x in issue.get('labels', [])}


def status_of(sid, issue, prs, after, done):
    """The status of a session from its issue; `done` is the set of sessions already Done."""
    if issue is None:
        return None
    lab = labels_of(issue)
    if issue['state'] == 'closed':
        return 'Done'
    if 'blocked' in lab:
        return 'Blocked'
    if any(p['state'] == 'open' for p in prs.get(sid, [])):
        return 'In review'
    if 'paused' in lab:
        return 'Paused'
    if 'running' in lab:
        return 'Running'
    if all(a in done for a in after) and 'hold' not in lab:
        return 'Ready'
    return 'Waiting'


def field(body, name):
    m = re.search(rf'^\W*{name}\W*:\W*(.+?)\s*$', body or '', re.M | re.I)
    return m.group(1).strip() if m else ''


def fix_rows(issues):
    """The rows of session-fixes.csv, from the fix issues. A fix issue is titled '<gate session>-F<n> Fix: <problem>'
    and its body has the lines 'Round:', 'Owner session:' and 'Gate line:'."""
    rows = []
    for sid, i in issues.items():
        if not FIX_RE.match(sid):
            continue
        rnd, owner, line = field(i['body'], 'Round'), field(i['body'], 'Owner session'), field(i['body'], 'Gate line')
        problem = re.sub(r'^\S+\s+(Fix:\s*)?', '', i['title']).strip()
        if not (rnd.isdigit() and owner and line and problem):
            print(f'  warning: fix issue #{i["number"]} ({sid}) lacks a Round, Owner session or Gate line; it is left out')
            continue
        rows.append(dict(fix=sid, round=rnd, owner_session=owner, gate_line=line, problem=problem))
    key = lambda r: (r['fix'].rsplit('-F', 1)[0], int(r['fix'].rsplit('-F', 1)[1]))
    return sorted(rows, key=key)


def write_csv(path, header, rows):
    old = open(path).read() if os.path.isfile(path) else ''
    lines = [header] + rows
    import io
    buf = io.StringIO()
    w = csv.writer(buf, lineterminator='\n')
    w.writerows(lines)
    if buf.getvalue() != old:
        open(path, 'w').write(buf.getvalue())
        return True
    return False


def body_of(repo, s, issues, fix):
    sid, group = s['session'], s['group']
    card = f'https://github.com/{repo}/blob/main/docs/implementation_plan/delivery/sessions/{group}.md#{sid.lower()}'
    after = ', '.join(f'#{issues[a]["number"]} {a}' if 'number' in issues.get(a, {}) else a for a in s['after'].split()) or 'nothing'
    out = [f'<!-- his-session {sid} -->',
           f'**Session {sid}** · {s["kind"]}' + (f' · slice {s["slice"]}' if s['slice'] else ''), '',
           f'Card: [{sid}]({card})', '', f'After: {after}']
    if fix:
        out += ['', f'Round: {fix["round"]}', f'Owner session: {fix["owner_session"]}', f'Gate line: {fix["gate_line"]}']
    if s['needs_a_person']:
        out += ['', f'Needs a person: {s["needs_a_person"]}']
    if s['safety_review']:
        out += ['', f'Safety review before merge: {s["safety_review"]}']
    out += ['', f'Start by hand: `python3 docs/implementation_plan/tools/launch_sessions.py start {sid}`', '',
            '_Written from the session plan by sync_github.py; a change made here is overwritten. Questions and answers go in the comments._']
    return '\n'.join(out)


def cmd_setup(a):
    repo = repo_slug()
    have = {x['name'] for x in get(f'repos/{repo}/labels?per_page=100')}
    want = dict(LABELS)
    for s in load_sessions():
        want.setdefault(kind_label(s['kind']), (KIND_COLOUR, f'Session kind: {s["kind"]}'))
        want.setdefault('flow:' + s['group'], (FLOW_COLOUR, f'Sessions of group {s["group"]}'))
    want.setdefault('kind:fix', (KIND_COLOUR, 'Session kind: Fix'))
    for name, (colour, desc) in want.items():
        if name not in have:
            send('POST', f'repos/{repo}/labels', dict(name=name, color=colour, description=desc))
            print(f'label {name}')
    cfg = config()
    if a.project_title and not cfg.get('project'):
        owner = repo.split('/')[0]
        if DRY:
            print(f'  would create project "{a.project_title}" for {owner} with the field "{STATUS_FIELD}"')
            return
        p = json.loads(gh('project', 'create', '--owner', owner, '--title', a.project_title, '--format', 'json').stdout)
        gh('project', 'field-create', str(p['number']), '--owner', owner, '--name', STATUS_FIELD,
           '--data-type', 'SINGLE_SELECT', '--single-select-options', ','.join(STATUSES))
        gh('project', 'link', str(p['number']), '--owner', owner, '--repo', repo, check=False)
        json.dump(dict(owner=owner, project=p['number']), open(CONFIG, 'w'), indent=2)
        open(CONFIG, 'a').write('\n')
        print(f'project {p["number"]} created: {p.get("url", "")}\nwrote {os.path.relpath(CONFIG)}; commit it. '
              f'In the project, add a board view with "{STATUS_FIELD}" as its column field.')
    print('setup done')


def sync_project(cfg, sessions, issues, status):
    owner, num = cfg['owner'], str(cfg['project'])
    pid = json.loads(gh('project', 'view', num, '--owner', owner, '--format', 'json').stdout)['id']
    fields = json.loads(gh('project', 'field-list', num, '--owner', owner, '--format', 'json').stdout)['fields']
    f = next((x for x in fields if x['name'] == STATUS_FIELD), None)
    if not f:
        print(f'  warning: project {num} has no field "{STATUS_FIELD}"; run setup')
        return 0
    opt = {o['name']: o['id'] for o in f.get('options', [])}
    items = json.loads(gh('project', 'item-list', num, '--owner', owner, '--format', 'json', '-L', '2000').stdout)['items']
    have = {}
    for it in items:
        n = (it.get('content') or {}).get('number')
        cur = next((v for k, v in it.items() if k.lower() == STATUS_FIELD.lower()), None)
        if n:
            have[n] = (it['id'], cur)
    changed = 0
    for s in sessions:
        sid = s['session']
        if sid not in issues or 'number' not in issues[sid]:
            continue
        n, st = issues[sid]['number'], status[sid]
        item, cur = have.get(n, (None, None))
        if cur == st:
            continue
        if st not in opt:
            print(f'  warning: the field "{STATUS_FIELD}" of project {num} has no option "{st}"; add it in the project settings')
            continue
        changed += 1
        if DRY:
            print(f'  would set project status of #{n} {sid} to {st}')
            continue
        if not item:
            item = json.loads(gh('project', 'item-add', num, '--owner', owner, '--url', issues[sid]['html_url'], '--format', 'json').stdout)['id']
        gh('project', 'item-edit', '--id', item, '--project-id', pid, '--field-id', f['id'], '--single-select-option-id', opt[st])
    return changed


def cmd_sync(a):
    repo = repo_slug()
    issues, prs = fetch(repo)
    known = {s['session'] for s in load_sessions()}

    # 2. fixes and status from GitHub into the plan, then the build
    fixes = fix_rows(issues)
    fixids = {r['fix'] for r in fixes}
    rows = []
    for sid, i in issues.items():
        if sid not in known and sid not in fixids:
            continue
        st = status_of(sid, i, prs, [], set())
        row = {'Done': 'Done', 'Blocked': 'Blocked', 'In review': 'In progress', 'Running': 'In progress', 'Paused': 'In progress'}.get(st)
        if row:
            merged = sorted((p for p in prs.get(sid, []) if p.get('merged_at')), key=lambda p: p['number'])
            rows.append((sid, row, f'#{merged[-1]["number"]}' if merged and row == 'Done' else '', f'issue #{i["number"]}'))
    if DRY:
        print(f'  would write {len(rows)} status rows and {len(fixes)} fix rows, and run the plan build')
    else:
        order = {s: n for n, s in enumerate(sorted(known | fixids))}
        ch = write_csv(FIXES_CSV, ['fix', 'round', 'owner_session', 'gate_line', 'problem'],
                       [[r['fix'], r['round'], r['owner_session'], r['gate_line'], r['problem']] for r in fixes])
        ch |= write_csv(STATUS_CSV, ['session', 'status', 'pull_request', 'notes'], sorted(rows, key=lambda r: order.get(r[0], 0)))
        if ch or a.build:
            r = subprocess.run([sys.executable, '-B', os.path.join(HERE, 'build.py')], capture_output=True, text=True)
            if r.returncode:
                sys.exit('sync_github.py: the plan build refused the state read from GitHub:\n' + (r.stdout + r.stderr).strip()[-1500:])

    # 3. issues for the slices that have work able to start
    sessions = load_sessions()
    fixby = {r['fix']: r for r in fixes}
    done = {s['session'] for s in sessions if s['session'] in issues and issues[s['session']]['state'] == 'closed'}
    groups = {s['slice'] or s['group'] for s in sessions
              if a.all or s['session'] in issues or all(x in done for x in s['after'].split())}
    miles = {m['title']: m['number'] for m in get(f'repos/{repo}/milestones?state=all&per_page=100')}
    sys.path.insert(0, os.path.join(HERE, 'definitions'))
    sys.dont_write_bytecode = True
    from slices_def import SLICES
    mtitle = {sl['id']: f'{sl["id"]} {sl["title"]}' for sl in SLICES}
    links = True
    created = updated = 0
    for s in sessions:
        sid, key = s['session'], s['slice'] or s['group']
        if key not in groups:
            continue
        ms = mtitle.get(key, f'{key} Foundation for agent work')
        if ms not in miles:
            m = send('POST', f'repos/{repo}/milestones', dict(title=ms))
            miles[ms] = m['number'] if m else 0
        title = f'{sid} {s["kind"]}: {s["title"]}'
        body = body_of(repo, s, issues, fixby.get(sid))
        managed = {kind_label(s['kind']), 'flow:' + s['group']} | ({'needs-person'} if s['needs_a_person'] else set()) \
            | ({'safety-review'} if s['safety_review'] else set())
        cur = issues.get(sid)
        if cur is None:
            new = send('POST', f'repos/{repo}/issues', dict(title=title, body=body, labels=sorted(managed), milestone=miles[ms] or None))
            created += 1
            issues[sid] = new or dict(title=title, state='open', labels=[dict(name=x) for x in managed])   # dry run: no number yet
            if new and links:
                for x in s['after'].split():
                    if x in issues and 'id' in issues[x]:
                        if send('POST', f'repos/{repo}/issues/{new["number"]}/dependencies/blocked_by', dict(issue_id=issues[x]['id']), check=False) is None:
                            print('  note: "blocked by" links are not available on this repository; the order is in each issue body')
                            links = False
                            break
            if new:
                time.sleep(float(os.environ.get('HIS_SYNC_PAUSE', '1')))   # stay under the limit on creating content
        else:
            st = status_of(sid, cur, prs, s['after'].split(), done)
            lab = labels_of(cur)
            keep = {x for x in lab if not (x.startswith(('kind:', 'flow:')) or x in ('needs-person', 'safety-review', 'ready'))}
            if st in ('Done', 'Blocked', 'In review', 'Paused'):
                keep.discard('running')
            if st in ('Done', 'Blocked', 'In review'):
                keep.discard('paused')
            want = keep | managed | ({'ready'} if st == 'Ready' else set())
            patch = {}
            if cur['title'] != title:
                patch['title'] = title
            if (cur.get('body') or '').replace('\r\n', '\n').strip() != body.strip():
                patch['body'] = body
            if want != lab:
                patch['labels'] = sorted(want)
            if (cur.get('milestone') or {}).get('title') != ms and miles[ms]:
                patch['milestone'] = miles[ms]
            if patch:
                send('PATCH', f'repos/{repo}/issues/{cur["number"]}', patch)
                updated += 1
                cur['labels'] = [dict(name=x) for x in want]

    # 4. status of every session that has an issue; `ready` on the issues just created
    status = {}
    for s in sessions:
        sid = s['session']
        if sid in issues:
            status[sid] = status_of(sid, issues[sid], prs, s['after'].split(), done)
            if status[sid] == 'Ready' and 'ready' not in labels_of(issues[sid]) and 'number' in issues[sid]:
                send('POST', f'repos/{repo}/issues/{issues[sid]["number"]}/labels', dict(labels=['ready']))
    cfg = config()
    board = 0
    if cfg.get('project'):
        try:
            board = sync_project(cfg, sessions, issues, status)
        except SystemExit as e:   # the board is a view: a failure there must not stop the sync
            print(f'  warning: the project board was not updated. {e}'.replace('\n', ' '))
            print('  The token needs access to the projects of the owner: the project and read:org scopes, '
                  'or for a fine-grained token, Projects read and write in the organisation permissions.')

    # 5. commit what step 2 changed
    if a.commit and not DRY:
        top = subprocess.run(['git', '-C', HERE, 'rev-parse', '--show-toplevel'], capture_output=True, text=True).stdout.strip()
        subprocess.run(['git', '-C', top, 'add', 'docs'], check=True)
        if subprocess.run(['git', '-C', top, 'diff', '--cached', '--quiet']).returncode:
            subprocess.run(['git', '-C', top, 'commit', '-q', '-m', 'Record the state of the sessions from GitHub.'], check=True)
            subprocess.run(['git', '-C', top, 'push', '-q', 'origin', 'HEAD:main'], check=True)
            print('committed and pushed the plan')
    count = {x: sum(1 for v in status.values() if v == x) for x in STATUSES}
    print(f'issues: {len(status)} of {len(sessions)} sessions (created {created}, updated {updated}, board changes {board})  '
          + '  '.join(f'{k}: {v}' for k, v in count.items() if v))


def main():
    global DRY
    p = argparse.ArgumentParser(description='Keep the GitHub issues of the sessions in step with the session plan.')
    sub = p.add_subparsers(dest='cmd', required=True)
    s = sub.add_parser('setup', help='create the labels and, with --project-title, the project board')
    s.add_argument('--project-title', help='create a project board with this title and record it in delivery/github.json')
    s.add_argument('--dry-run', action='store_true')
    s.set_defaults(fn=cmd_setup)
    s = sub.add_parser('sync', help='read the state from GitHub into the plan and bring the issues up to date')
    s.add_argument('--dry-run', action='store_true', help='read from GitHub, change nothing there or here')
    s.add_argument('--all', action='store_true', help='create the issues of every slice, not only of those with work able to start')
    s.add_argument('--build', action='store_true', help='run the plan build even when the state read from GitHub changed nothing')
    s.add_argument('--commit', action='store_true', help='commit and push the status files and the rebuilt plan when they changed')
    s.set_defaults(fn=cmd_sync)
    a = p.parse_args()
    DRY = a.dry_run
    a.fn(a)


if __name__ == '__main__':
    main()
