"""Link real pushed store commits to today's three requirements and six tasks."""
import json
import subprocess
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
REPO = ROOT.parent / 'zhctproject/store'
sys.path.insert(0, str(ROOT / 'work_store/VWCG-1450-consume-order-department-bulk-select/yunxiao'))
from transport import api, PREFIX, ORG, compact

STATE = HERE / 'today-code-links.sanitized.json'
state = json.loads(STATE.read_text()) if STATE.exists() else {'commits': {}, 'items': {}}
GROUPS = [
    (['VWCG-1450', 'VWCG-1452', 'VWCG-1453'], ['974d09a4d', '030d2276d', 'bf5b71ceb']),
    (['VWCG-1454', 'VWCG-1455', 'VWCG-1456'], ['ae82cb12e']),
    (['VWCG-1451', 'VWCG-1457', 'VWCG-1458'], ['cc12d576a', 'c64aa65f7']),
]


def save():
    STATE.write_text(json.dumps(state, ensure_ascii=False, indent=2) + '\n')


def git(*args):
    return subprocess.check_output(['git', '-C', str(REPO), *args], text=True).strip()


def as_list(value):
    return value if isinstance(value, list) else (value or {}).get('result', (value or {}).get('items', []))


def relations(item_id):
    errors = []
    for prefix in [PREFIX + '/workitems/', '/oapi/v1/projex/workitems/']:
        try:
            return prefix, as_list(api('GET', prefix + item_id + '/extRelationRecords?category=codeupCommit'))
        except RuntimeError as error:
            errors.append(str(error))
    raise RuntimeError('; '.join(errors))


assert git('branch', '--show-current') == 'guoxin_develop'
head = git('rev-parse', 'HEAD')
remote = git('ls-remote', '--heads', 'origin', 'refs/heads/guoxin_develop').split()[0]
assert head == remote, 'Push readback must match before code linking'
repository = api('GET', f'/oapi/v1/codeup/organizations/{ORG}/repositories/4913137')
assert repository['pathWithNamespace'] == ORG + '/zhct/store'
state['branch'] = 'guoxin_develop'
state['localHead'] = head
state['remoteHead'] = remote
state['repositoryId'] = 4913137
save()

for serials, short_shas in GROUPS:
    commits = []
    for short in short_shas:
        sha = git('rev-parse', short)
        subprocess.check_call(['git', '-C', str(REPO), 'merge-base', '--is-ancestor', sha, 'origin/guoxin_develop'])
        verified = api('GET', f'/oapi/v1/codeup/organizations/{ORG}/repositories/4913137/commits/{sha}')
        assert verified.get('id', verified.get('sha')) == sha, 'Codeup commit mismatch'
        entry = {'sha': sha, 'subject': git('show', '-s', '--format=%s', sha),
                 'projectId': '4913137', 'url': repository['webUrl'] + '/commit/' + sha,
                 'codeupReadbackConfirmed': True, 'inRemoteBranch': True}
        state['commits'][short] = entry
        save()
        commits.append(entry)
    for serial in serials:
        item = api('GET', PREFIX + '/workitems/' + serial)
        assert item['assignedTo']['name'] == '兰海军'
        prefix, before = relations(item['id'])
        for commit in commits:
            if not any(r.get('businessId', r.get('commitSha')) == commit['sha']
                       and str(r.get('projectId')) == '4913137' for r in before):
                api('POST', prefix + item['id'] + '/extRelationRecords', {
                    'category': 'codeupCommit', 'projectId': '4913137',
                    'commitSha': commit['sha'], 'title': commit['subject'], 'url': commit['url'],
                })
        _, after = relations(item['id'])
        for commit in commits:
            assert any(r.get('businessId', r.get('commitSha')) == commit['sha']
                       and str(r.get('projectId')) == '4913137' for r in after), 'Missing native link: ' + serial
        state['items'][serial] = {**compact(item), 'verifiedCommitShas': [c['sha'] for c in commits],
                                 'storeCommitRelationCount': sum(str(r.get('projectId')) == '4913137' for r in after)}
        save()
        marker = 'GUOXIN-20261019-STORE-CODE-LINK'
        comments_path = PREFIX + '/workitems/' + item['id'] + '/comments'
        comments = as_list(api('GET', comments_path))
        if not any(marker in str(c.get('content', '')) for c in comments):
            content = (marker + '\n已补齐真实业务代码关联并回读确认，仓库 zhct/store（4913137），'
                       '全部提交已在 origin/guoxin_develop。\n' +
                       '\n'.join(c['sha'] + ' ' + c['subject'] + '\n' + c['url'] for c in commits) +
                       '\n不是仅写评论：extRelationRecords/codeupCommit 已回读 SHA 与仓库ID。'
                       '\n当前状态保留：' + item['status']['name'] + '。未创建新MR、未部署。'
                       '\n本轮退款相关回归：PHP136项/前端60项及既有Node14构建通过；全仓26项基线失败无新增，'
                       '未完成的环境验收仍待补，不声称已发布。'
                       '\n证据：work_store/20261019-guoxin-refund-person-columns/submission.md。')
            result = api('POST', comments_path, {'content': content})
            state['items'][serial]['commentId'] = result.get('id') if isinstance(result, dict) else result
            save()
        comments = as_list(api('GET', comments_path))
        assert any(marker in str(c.get('content', '')) for c in comments)
        state['items'][serial]['commentReadbackConfirmed'] = True
        save()
        print(serial, 'store commits verified:', len(commits), flush=True)

assert len(state['items']) == 9
state['allNineReadbackConfirmed'] = True
save()
