"""Idempotent task setup using the verified personal-token OpenAPI 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 = '94b420ee646b20087cbed3a5be'
OWNER = '635755195dc8531eeb2e33d9'
STATE = HERE / 'items.sanitized.json'
state = json.loads(STATE.read_text()) if STATE.exists() else {'tasks': {}}

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

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

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

def check(item):
    for marker in ['Use Case', 'UC-SUBSIDY-026', '主流程', '异常/恢复', '验收标准', '测试矩阵', 'DoR', 'READY']:
        assert marker in item.get('description', ''), marker
    assert item['assignedTo']['id'] == OWNER

parent = api('GET', PREFIX+'/workitems/VWCG-1462')
assert parent['id'] == PARENT and parent['space']['id'] == SPACE
assert not parent.get('description') or 'UC-SUBSIDY-026' in parent['description'], 'Unexpected parent edits; preserve and review'
state.setdefault('before', compact(parent)); save()
api('PUT', PREFIX+'/workitems/'+PARENT, {
    'description': rich((HERE/'parent-use-case.md').read_text()), 'formatType': 'RICHTEXT', 'assignedTo': OWNER,
})
parent = api('GET', PREFIX+'/workitems/'+PARENT); 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 child search pagination')
for key, title, document, estimate in [
    ('development', '开发与自测：补贴充值方式标记及查询导出', 'development-task.md', 4),
    ('validation', '测试与验收：补贴充值方式及资金不变量', 'validation-task.md', 2),
]:
    matches = [i for i in children if i['subject'] == title]
    assert len(matches) <= 1
    item_id = state['tasks'].get(key, {}).get('id') or (matches[0]['id'] if matches else None)
    if not item_id:
        result = api('POST', PREFIX+'/workitems', {
            'spaceId': SPACE, 'workitemTypeId': 'ba102e46bc6a8483d9b7f25c',
            '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'},
        })
        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(s['id'] == '100010' for s 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': estimate, 'owner': OWNER, 'description': '未使用AI的完整分析、设计、实施、自测审查或验收预计投入；非实际工时。',
        })
    item = api('GET', PREFIX+'/workitems/'+item_id)
    fields = {f['fieldId']: f['values'][0]['identifier'] for f in item['customFieldValues'] if f.get('values')}
    assert fields['79'].startswith('2026-10-19') and fields['80'].startswith('2026-10-19')
    assert float(fields['101586']) == estimate
    state['tasks'][key] = {**compact(item), 'planStart': '2026-10-19', 'planEnd': '2026-10-19', 'estimatedHours': estimate}
    save()
    print(item['serialNumber'], item['subject'], 'assigned to', item['assignedTo']['name'], flush=True)
print(json.dumps(state, ensure_ascii=False, indent=2))
