"""Prepare and verify VWCG-1454 child tasks using the established local transport."""
import html
import json
import sys
from pathlib import Path

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

STATE_PATH = WORK / 'items.sanitized.json'
state = json.loads(STATE_PATH.read_text()) if STATE_PATH.exists() else {'tasks': {}}

def save():
    STATE_PATH.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 render(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)

if __name__ == '__main__':
    parent = api('GET', PREFIX + '/workitems/VWCG-1454')
    assert parent['space']['id'] == SPACE
    owner = parent['assignedTo']['id']
    parent_id = parent['id']
    body = render((WORK / 'use-case.md').read_text())
    api('PUT', PREFIX + '/workitems/' + parent_id, {'description': body, 'formatType': 'RICHTEXT'})
    parent = api('GET', PREFIX + '/workitems/VWCG-1454')
    for marker in ['Use Case ID', '主流程', '异常/恢复', '验收标准', '测试矩阵', 'DoR', 'READY']:
        assert marker in parent['description'], marker
    state['parent'] = compact(parent)
    save()
    all_tasks = rows(api('POST', PREFIX + '/workitems:search', {'spaceId': SPACE, 'category': 'Task', 'page': 1, 'perPage': 200, 'orderBy': 'gmtCreate', 'sort': 'desc'}))
    plans = [
        ('development', '开发与自测：五类统计报表部门全选反选', 4, 'development-task.md'),
        ('validation', '回归与导出验收：五类报表部门筛选', 2, 'validation-task.md'),
    ]
    for key, title, estimate, filename in plans:
        existing = state['tasks'].get(key) or next((t for t in all_tasks if t.get('parentId') == parent_id and t.get('subject') == title), None)
        if existing:
            task_id = existing['id']
        else:
            created = api('POST', PREFIX + '/workitems', {
                'spaceId': SPACE, 'workitemTypeId': 'ba102e46bc6a8483d9b7f25c',
                'subject': title, 'description': (WORK / filename).read_text(), 'documentFormat': 'MARKDOWN',
                'assignedTo': owner, 'status': '100005', 'participants': [owner], 'parentId': parent_id,
                'customFieldValues': {'79': '2026-10-19', '80': '2026-10-19'},
            })
            task_id = created.get('id', created.get('identifier')) if isinstance(created, dict) else created
            assert task_id
            state['tasks'][key] = {'id': task_id}
            save()
        task = api('GET', PREFIX + '/workitems/' + task_id)
        assert task['parentId'] == parent_id and task['assignedTo']['id'] == owner
        for marker in ['Use Case ID', '主流程', '异常/恢复', '验收标准', '测试矩阵', 'DoR']:
            assert marker in task['description'], marker
        endpoint = PREFIX + '/workitems/' + task_id + '/estimatedEfforts'
        if not rows(api('GET', endpoint)):
            api('POST', endpoint, {'spentTime': estimate, 'owner': owner, 'description': '按无AI完整流程估算，包含需求理解、方案设计、实现、自测、回归及交付；实际工时另据执行记录登记。'})
        task = api('GET', PREFIX + '/workitems/' + task_id)
        fields = {x['fieldId']: x.get('values') for x in task.get('customFieldValues', []) if x.get('fieldId') in ['79', '80', '101586']}
        assert all(k in fields for k in ['79', '80', '101586'])
        state['tasks'][key] = {**compact(task), 'planFields': fields, 'estimateReadback': api('GET', endpoint)}
        save()
    print(json.dumps({'parent': state['parent'], 'tasks': {k: compact(v) for k, v in state['tasks'].items()}}, ensure_ascii=False, indent=2))
