"""Verify the same-branch push, attach native commits, and hand VWCG-1459 to QA."""
import html
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

items = json.loads((HERE / 'items.sanitized.json').read_text())
STATE = HERE / 'delivery.sanitized.json'
state = json.loads(STATE.read_text()) if STATE.exists() else {'items': {}}


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 rows(value):
    return value if isinstance(value, list) else (value or {}).get('result', (value or {}).get('items', []))


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


assert git('branch', '--show-current') == 'guoxin_develop'
sha = git('rev-parse', 'HEAD')
subject = git('show', '-s', '--format=%s', sha)
assert subject.startswith('#' + items['tasks']['development']['serialNumber'] + ' ')
remote = git('ls-remote', '--heads', 'origin', 'refs/heads/guoxin_develop').split()[0]
assert sha == remote
repo = api('GET', f'/oapi/v1/codeup/organizations/{ORG}/repositories/4913137')
assert repo['pathWithNamespace'] == ORG + '/zhct/store'
commit = api('GET', f'/oapi/v1/codeup/organizations/{ORG}/repositories/4913137/commits/{sha}')
assert commit.get('id', commit.get('sha')) == sha
url = repo['webUrl'] + '/commit/' + sha
state.update({'branch': 'guoxin_develop', 'commit': sha, 'subject': subject, 'remoteHead': remote,
              'repositoryId': 4913137, 'commitUrl': url, 'codeupReadbackConfirmed': True})
save()

for key, item, target, document in [
    ('parent', items['parent'], '1dec9023be7be6cf79e6bde901', 'parent-use-case.md'),
    ('development', items['tasks']['development'], '100011', 'development-task.md'),
    ('validation', items['tasks']['validation'], '100010', 'validation-task.md'),
]:
    current = api('GET', PREFIX + '/workitems/' + item['id'])
    assert current['assignedTo']['name'] == '兰海军'
    workflow = api('GET', PREFIX + '/workitems/' + item['id'] + '/workflow')
    assert any(i['id'] == target for i in workflow['statuses'])
    assert current['status']['id'] in ['100005', '100010', '142838', target], 'Do not rewind advanced state'
    prefix, previous = relation(item['id'])
    if not any(r.get('businessId', r.get('commitSha')) == sha and str(r.get('projectId')) == '4913137' for r in previous):
        api('POST', prefix + item['id'] + '/extRelationRecords', {
            'category': 'codeupCommit', 'projectId': '4913137', 'commitSha': sha, 'title': subject, 'url': url,
        })
    _, after = relation(item['id'])
    assert any(r.get('businessId', r.get('commitSha')) == sha and str(r.get('projectId')) == '4913137' for r in after)
    text = (HERE / document).read_text() + '\n## 已交付代码\n- origin/guoxin_develop：' + sha + '\n- ' + url + '\n- 未新建MR或部署；真实业务1500条完整容量验收待补。\n'
    body = ''.join('<h2>' + html.escape(s[3:]) + '</h2>' if s.startswith('## ')
                   else '<p>' + html.escape(s) + '</p>' for s in text.splitlines() if s)
    api('PUT', PREFIX + '/workitems/' + item['id'], {'description': body, 'formatType': 'RICHTEXT', 'status': target})
    result = api('GET', PREFIX + '/workitems/' + item['id'])
    assert result['status']['id'] == target
    for marker in ['UC-ORDER-025', 'Use Case', '主流程', '异常/恢复', '验收标准', '测试矩阵', 'DoR', sha]:
        assert marker in result['description'], marker
    marker = 'VWCG1459-DELIVERY-' + sha[:9]
    path = PREFIX + '/workitems/' + item['id'] + '/comments'
    previous_comments = rows(api('GET', path))
    if not any(marker in str(c.get('content', '')) for c in previous_comments):
        api('POST', path, {'content': marker + '\nUC-ORDER-025 v1.0，已开发提交并原生关联真实store代码，非仅评论关联。\n' +
             subject + '\n' + sha + '\n' + url + '\n分支：guoxin_develop→origin/guoxin_develop，本地远端SHA一致。'
             '\n计划2026-10-19开始/完成，开发和测试非AI预计各1h。实际工时不以预计冒充，尚未补登记。'
             '\n验证：真实1500行xlsx/1501拒绝/末行错误整批失败；后端150项/863断言、前端62项及Node14构建通过。'
             '\n全仓26项既有失败无新增；1500条真实业务入库/审核/扣款和HTTP容量未验收，测试任务继续处理中。'
             '\n父需求待测试，开发子任务开发完成；没有新建MR或部署，未改变审核/扣款/事务逻辑。'
             '\n证据：work_store/20261019-guoxin-supplement-import-1500/summary.md。'})
    comments = rows(api('GET', path))
    assert any(marker in str(c.get('content', '')) for c in comments)
    state['items'][key] = {**compact(result), 'commitRelationConfirmed': True, 'commentReadbackConfirmed': True}
    save()
    print(item['serialNumber'], result['status']['name'], 'native commit verified', flush=True)

items['parent'] = state['items']['parent']
for key in ['development', 'validation']:
    items['tasks'][key].update(state['items'][key])
(HERE / 'items.sanitized.json').write_text(json.dumps(items, ensure_ascii=False, indent=2) + '\n')
state['allThreeReadbackConfirmed'] = True
save()
