#!/usr/bin/python3

from __future__ import annotations

import json
import asyncio
from collections import defaultdict
import re

import const
from agithub import GitHub

PKG_RE = re.compile(r'^(?:>\s*)?[*-]\s+\[([ xX])\]\s+(\S+)')

async def main() -> None:
  gh = GitHub(const.GITHUB_TOEKN)
  comments = [c async for c in gh.get_issue_comments(
    'archlinuxcn/repo', const.ISSUE_NR)
  ]
  removed = defaultdict(list)
  waiting_user = []

  for comment in comments:
    lines = comment.body.splitlines()

    if comment.author == 'lilydjwg' and not lines[0].endswith(':'):
      continue

    if comment.author == 'lilydjwg':
      who = lines[0][1:].rstrip(': ')
    else:
      who = comment.author

    all_unchecked = True
    has_package = False
    for l in lines:
      if not l.strip():
        continue
      m = PKG_RE.match(l)
      if not m:
        continue

      checked = m.group(1) != ' '
      name = m.group(2)
      has_package = True
      # print(who, name, checked)
      if not checked:
        removed[who].append(name)
      else:
        all_unchecked = False
        try:
          removed[who].remove(name)
        except ValueError:
          pass

    if not has_package:
      continue

    if all_unchecked:
      waiting_user.append(who)
    else:
      try:
        waiting_user.remove(who)
      except ValueError:
        pass

  with open('/home/lilydjwg/tmpfs/removed.json', 'w') as f:
    json.dump({'removed': removed, 'waiting_user': waiting_user}, f)

if __name__ == '__main__':
  asyncio.run(main())
