"""Task-scoped, idempotent Yunxiao bookkeeping; no business Git operations."""
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, SPACE, compact

PARENT = '25f078d5e3045bd2c9b2f0013c'
OWNER = '635755195dc8531eeb2e33d9'
TASK_TYPE = 'ba102e46bc6a8483d9b7f25c'
STATE = HERE / 'cloud-items.sanitized.json'
state = json.loads(STATE.read_text()) if STATE.exists() else {'tasks': {}}


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


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


def richtext(source):
    return ''.join('<h2>' + html.escape(line[3:]) + '</h2>' if line.startswith('## ')
                   else '<p>' + html.escape(line) + '</p>' for line in source.splitlines() if line)


def check_body(item):
    for marker in ['UC-ORDER-024', 'Use Case', '主流程', '异常/恢复', '验收标准', '测试矩阵', 'DoR', 'READY']:
        if marker not in item.get('description', ''):
            raise RuntimeError('Missing UC marker: ' + marker)


parent = api('GET', PREFIX + '/workitems/VWCG-1451')
assert parent['id'] == PARENT and parent['assignedTo']['id'] == OWNER
assert parent['space']['id'] == SPACE
if 'before' not in state:
    state['before'] = {'parent': compact(parent), 'description': parent.get('description', '')}
    save()
if parent.get('description') and 'UC-ORDER-024' not in parent['description']:
    raise RuntimeError('Parent acquired an unrelated body; preserve and review before replacing')
if parent['status']['id'] not in ['100005', '142838']:
    raise RuntimeError('Parent already advanced; do not rewind its workflow on replay')
workflow = api('GET', PREFIX + '/workitems/' + PARENT + '/workflow')
assert any(i['id'] == '142838' for i in workflow['statuses'])
api('PUT', PREFIX + '/workitems/' + PARENT, {
    'description': richtext((HERE / 'parent-use-case.md').read_text()),
    'formatType': 'RICHTEXT', 'assignedTo': OWNER, 'status': '142838',
})
parent = api('GET', PREFIX + '/workitems/VWCG-1451')
check_body(parent)
state['parent'] = compact(parent)
save()

children = []
for page in range(1, 31):
    batch = rows(api('POST', PREFIX + '/workitems:search', {
        'spaceId': SPACE, 'category': 'Task', 'page': page, 'perPage': 200,
        'orderBy': 'gmtCreate', 'sort': 'desc',
    }))
    children.extend(i for i in batch if i.get('parentId') == PARENT)
    if len(batch) < 200:
        break
else:
    raise RuntimeError('Task pagination incomplete; do not create duplicates')

for key, title, document, estimate in [
    ('development', '开发：退款订单筛选与部门手机号列表导出', 'development-task.md', 2),
    ('validation', '测试：退款订单筛选、列表与导出对账回归', 'validation-task.md', 1),
]:
    known = state['tasks'].get(key)
    matches = [i for i in children if i['subject'] == title]
    if len(matches) > 1:
        raise RuntimeError('Duplicate child tasks need review')
    task_id = known['id'] if known else (matches[0]['id'] if matches else None)
    if not task_id:
        result = api('POST', PREFIX + '/workitems', {
            'spaceId': SPACE, 'workitemTypeId': TASK_TYPE, 'subject': title,
            'description': (HERE / document).read_text(), 'documentFormat': 'MARKDOWN',
            'assignedTo': OWNER, 'participants': [OWNER], 'parentId': PARENT,
            'status': '100005', 'customFieldValues': {'79': '2026-10-19', '80': '2026-10-19'},
        })
        task_id = str(result.get('id', result.get('identifier')) if isinstance(result, dict) else result)
        if not task_id or task_id == 'None':
            raise RuntimeError('Task creation returned no ID')
        state['tasks'][key] = {'id': task_id, 'subject': title}
        save()
    item = api('GET', PREFIX + '/workitems/' + task_id)
    assert item['parentId'] == PARENT and item['assignedTo']['id'] == OWNER
    check_body(item)
    task_workflow = api('GET', PREFIX + '/workitems/' + task_id + '/workflow')
    assert any(i['id'] == '100010' for i in task_workflow['statuses'])
    if item['status']['id'] == '100005':
        api('PUT', PREFIX + '/workitems/' + task_id, {'status': '100010'})
    efforts = rows(api('GET', PREFIX + '/workitems/' + task_id + '/estimatedEfforts'))
    if not efforts:
        api('POST', PREFIX + '/workitems/' + task_id + '/estimatedEfforts', {
            'spentTime': estimate, 'owner': OWNER,
            'description': '非AI完整投入估算；开发包括分析、实现、契约、自审；测试包括设计、边界、实际XLSX与回归。不是实际工时。',
        })
    item = api('GET', PREFIX + '/workitems/' + task_id)
    state['tasks'][key] = {
        **compact(item), 'customFieldValues': item.get('customFieldValues'),
        'estimatedHours': estimate,
        'estimateReadback': api('GET', PREFIX + '/workitems/' + task_id + '/estimatedEfforts'),
        'actualEffort': '未伪填，后续按可核实真实投入补充',
    }
    save()

comment = ('VWCG-1451 / UC-ORDER-024 v1.0：已补需求正文和开发、测试切片，均指派兰海军，'
           '计划2026-10-19开始/完成，非AI预计开发2h、测试1h。退款三方类型筛选已在既有代码支持；'
           '本次部门和手机号列表/导出补充目前在本地guoxin_develop未提交。'
           '国信后端136项/前端60项及Node14构建通过，SQLite真实测试数据与实际XLSX已核验；'
           '全仓26项基线失败无新增，环境实页/下载/截图验收待补。'
           '本轮只办理云效任务，不提交、推送、创建MR或部署。'
           '父需求开发中、两任务处理中，不将本地通过写成已发布。'
           '证据：work_store/20261019-guoxin-refund-person-columns/summary.md。')
for key, item in [('parent', state['parent'])] + list(state['tasks'].items()):
    state.setdefault('comments', {})
    if key not in state['comments']:
        response = api('POST', PREFIX + '/workitems/' + item['id'] + '/comments', {'content': comment})
        state['comments'][key] = response
        save()
    comments = rows(api('GET', PREFIX + '/workitems/' + item['id'] + '/comments'))
    if not any('UC-ORDER-024' in str(i.get('content', '')) for i in comments):
        raise RuntimeError('Comment readback not confirmed for ' + key)
state['commentReadbackConfirmed'] = True
save()
print(json.dumps({'parent': state['parent'], 'tasks': state['tasks'],
                  'commentReadbackConfirmed': True}, ensure_ascii=False, indent=2))
