"""Create/read back VWCG-1459 child tasks through the verified OpenAPI CLI transport."""
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 = '65d0a12c531aea92fce4be4bc0'
OWNER = '635755195dc8531eeb2e33d9'
STATE = HERE / '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 check(item):
    for marker in ['Use Case', 'UC-ORDER-025', '主流程', '异常/恢复', '验收标准', '测试矩阵', 'DoR', 'READY']:
        assert marker in item.get('description', ''), marker
    assert item['assignedTo']['id'] == OWNER


parent = api('GET', PREFIX + '/workitems/VWCG-1459')
assert parent['id'] == PARENT and parent['space']['id'] == SPACE
if parent.get('description') and 'UC-ORDER-025' not in parent['description']:
    raise RuntimeError('Parent acquired other text; review before replacing')
assert parent['status']['id'] in ['100005', '142838']
state.setdefault('before', compact(parent))
save()
body = ''.join('<h2>' + html.escape(s[3:]) + '</h2>' if s.startswith('## ')
               else '<p>' + html.escape(s) + '</p>'
               for s in (HERE / 'parent-use-case.md').read_text().splitlines() if s)
api('PUT', PREFIX + '/workitems/' + PARENT, {'description': body, 'formatType': 'RICHTEXT', 'assignedTo': OWNER})
parent = api('GET', PREFIX + '/workitems/VWCG-1459')
check(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('Incomplete pagination')
for key, title, doc in [
    ('development', '开发与自测：两类消费机补单导入上限1500', 'development-task.md'),
    ('validation', '边界与导入验收：堂食便利店1500条批量补单', 'validation-task.md'),
]:
    found = [i for i in children if i['subject'] == title]
    assert len(found) <= 1
    item_id = state['tasks'].get(key, {}).get('id') or (found[0]['id'] if found else None)
    if not item_id:
        result = api('POST', PREFIX + '/workitems', {
            'spaceId': SPACE, 'workitemTypeId': 'ba102e46bc6a8483d9b7f25c',
            'subject': title, 'description': (HERE / doc).read_text(), 'documentFormat': 'MARKDOWN',
            'assignedTo': OWNER, 'participants': [OWNER], 'parentId': PARENT, 'status': '100005',
            'customFieldValues': {'79': '2026-10-19', '80': '2026-10-19'},
        })
        item_id = str(result.get('id', result.get('identifier')) if isinstance(result, dict) else result)
        assert item_id and item_id != 'None'
        state['tasks'][key] = {'id': item_id}
        save()
    item = api('GET', PREFIX + '/workitems/' + item_id)
    check(item)
    assert item['parentId'] == PARENT
    workflow = api('GET', PREFIX + '/workitems/' + item_id + '/workflow')
    assert any(i['id'] == '100010' for i in workflow['statuses'])
    if item['status']['id'] == '100005':
        api('PUT', PREFIX + '/workitems/' + item_id, {'status': '100010'})
    if not rows(api('GET', PREFIX + '/workitems/' + item_id + '/estimatedEfforts')):
        api('POST', PREFIX + '/workitems/' + item_id + '/estimatedEfforts', {
            'spentTime': 1, 'owner': OWNER, 'description': '未使用AI的完整分析/实现/审查或测试设计/文件边界/回归与验收预计投入，非实际工时。',
        })
    item = api('GET', PREFIX + '/workitems/' + item_id)
    fields = {f['fieldId']: f['values'][0]['identifier'] for f in item['customFieldValues']}
    assert fields['79'].startswith('2026-10-19') and fields['80'].startswith('2026-10-19')
    assert float(fields['101586']) == 1
    state['tasks'][key] = {**compact(item), 'planStart': '2026-10-19', 'planEnd': '2026-10-19',
                           'estimatedHours': 1, 'estimateReadback': api('GET', PREFIX + '/workitems/' + item_id + '/estimatedEfforts')}
    save()
print(json.dumps({'parent': state['parent'], 'tasks': state['tasks']}, ensure_ascii=False, indent=2))
