"""Apply the user's explicit local-development-complete handoff status."""
import html
import json
import sys
from pathlib import Path

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

STATE = HERE / 'status-correction.sanitized.json'
state = json.loads(STATE.read_text()) if STATE.exists() else {'items': {}}
OWNER = '635755195dc8531eeb2e33d9'
targets = [
    ('VWCG-1451', '1dec9023be7be6cf79e6bde901', '待测试', 'parent-use-case.md'),
    ('VWCG-1457', '100011', '开发完成', 'development-task.md'),
    ('VWCG-1458', '100010', '处理中', None),
]


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


for serial, status_id, status_name, document in targets:
    item = api('GET', PREFIX + '/workitems/' + serial)
    assert item['assignedTo']['id'] == OWNER
    state['items'].setdefault(serial, {'before': compact(item)})
    save()
    if document:
        workflow = api('GET', PREFIX + '/workitems/' + item['id'] + '/workflow')
        assert any(i['id'] == status_id and i['name'] == status_name for i in workflow['statuses'])
        if item['status']['id'] not in ['142838', '100010', status_id]:
            raise RuntimeError('Work item advanced unexpectedly; do not rewind: ' + serial)
        description = ''.join('<h2>' + html.escape(line[3:]) + '</h2>' if line.startswith('## ')
                              else '<p>' + html.escape(line) + '</p>'
                              for line in (HERE / document).read_text().splitlines() if line)
        api('PUT', PREFIX + '/workitems/' + item['id'], {
            'status': status_id, 'description': description, 'formatType': 'RICHTEXT',
        })
    item = api('GET', PREFIX + '/workitems/' + serial)
    assert item['status']['id'] == status_id and item['status']['name'] == status_name
    assert item['assignedTo']['id'] == OWNER
    if document:
        assert 'UC-ORDER-024' in item['description'] and 'DoR' in item['description']
    state['items'][serial]['after'] = compact(item)
    save()
    comment = ('按用户确认修正交测状态：VWCG-1451待测试，VWCG-1457开发完成，VWCG-1458继续处理中。'
               '本地开发和相关验证已完成（国信后端136项、前端60项、真实SQLite/XLSX与Node14构建通过）。'
               '全仓26项基线失败无新增，非全仓全绿。代码仍在本地guoxin_develop未提交，'
               '正式提交关联及环境页面/下载验收待办；本次状态流转不代表已合并或已发布，不操作业务Git或部署。')
    if 'comment' not in state['items'][serial]:
        state['items'][serial]['comment'] = api('POST', PREFIX + '/workitems/' + item['id'] + '/comments', {'content': comment})
        save()
    comments = api('GET', PREFIX + '/workitems/' + item['id'] + '/comments') or []
    comments = comments if isinstance(comments, list) else comments.get('result', comments.get('items', []))
    assert any('按用户确认修正交测状态' in str(c.get('content', '')) for c in comments)
    state['items'][serial]['commentReadbackConfirmed'] = True
    save()

original = json.loads((HERE / 'cloud-items.sanitized.json').read_text())
original['parent'] = state['items']['VWCG-1451']['after']
for key, serial in [('development', 'VWCG-1457'), ('validation', 'VWCG-1458')]:
    original['tasks'][key].update(state['items'][serial]['after'])
original['latestStatusEvidence'] = 'status-correction.sanitized.json'
(HERE / 'cloud-items.sanitized.json').write_text(json.dumps(original, ensure_ascii=False, indent=2) + '\n')
print(json.dumps({k: v['after']['status']['name'] for k, v in state['items'].items()}, ensure_ascii=False))
