# -*- coding: utf-8 -*-
"""Finalize only the four task-owned items, with idempotent comment readback."""
import json,subprocess
from pathlib import Path
from transport import api,PREFIX,compact,SPACE
HERE=Path(__file__).resolve().parent
state=json.loads((HERE/'items.sanitized.json').read_text())
commits=json.loads((HERE/'commits.sanitized.json').read_text())
actuals=json.loads((HERE/'actual-effort-readback.sanitized.json').read_text())
owner='635755195dc8531eeb2e33d9'
files={'parent':'parent-requirement.md','analysis':'analysis-task.md','development':'development-task.md','validation':'validation-task.md'}
code='\n'.join(f'- {repo}：{c["branch"]}，[{c["sha"][:9]}]({c["url"]})' for repo,c in commits.items())
total=round(sum(x['actualTime'] for x in actuals.values()),1)
marker='20261015-RECEIPT-DELIVERY-v1'
receipt=f'''## 代码与交付回读（2026-10-15）

{code}

三项子任务均指派兰海军，预计4/8/4小时，共16小时；实际AI辅助执行工时共{total}小时，按阶段根线程有效执行时间登记，不叠加并行角色。

开发库专项7项909断言通过，保留8档口、213订单、217明细、2取餐记录；PC实际保存回显及ai_api跨库读取通过。提交前store订单/档口编辑/一卡通路由、ai_api及Vue专项复核通过。实际外部扣款、物理出纸、Redis并发及生产验收不在本次证据内；范围外已有测试问题见开发库验收报告。

用户明确MR自行创建：代码已推送两仓库各自origin/develop_binzhou，未创建MR、未推送release、未合并或生产部署。父需求保持待测试，子任务记录开发完成，不代表生产验收结束。
'''
result={}
for key in files:
    item=state['parent'] if key=='parent' else state['tasks'][key]
    path=PREFIX+'/workitems/'+item['id']
    md=(HERE/files[key]).read_text()
    heading='## 代码与交付回读（2026-10-15）'
    md=md.split(heading)[0].rstrip()+'\n\n'+receipt
    (HERE/files[key]).write_text(md)
    html=subprocess.run(['node','--input-type=module','-e',"import { marked } from '/Users/wiscourper/.cache/codex-runtimes/codex-primary-runtime/dependencies/node/node_modules/marked/lib/marked.esm.js'; let s='';for await(const c of process.stdin)s+=c;process.stdout.write(marked.parse(s));"],input=md,text=True,capture_output=True,check=True).stdout
    api('PUT',path,{'description':html})
    desired='1dec9023be7be6cf79e6bde901' if key=='parent' else '100011'
    live=api('GET',path)
    if live.get('status',{}).get('id')!=desired:api('PUT',path,{'status':desired})
    live=api('GET',path)
    assert live['assignedTo']['id']==owner
    assert live['status']['id']==desired
    assert '<h2>' in live['description'] and 'UC-RECEIPT-001' in live['description']
    assert all(c['sha'][:9] in live['description'] for c in commits.values())
    comment=marker+'\n'+receipt
    comments=api('GET',path+'/comments') or []
    if not isinstance(comments,list):comments=comments.get('result',comments.get('items',[]))
    found=[x for x in comments if marker in str(x.get('content',''))]
    if not found:api('POST',path+'/comments',{'content':comment})
    comments=api('GET',path+'/comments') or []
    if not isinstance(comments,list):comments=comments.get('result',comments.get('items',[]))
    found=[x for x in comments if marker in str(x.get('content',''))]
    assert len(found)==1,'Comment readback missing or duplicate'
    record=compact(live)
    record['url']=f'https://devops.aliyun.com/projex/project/{SPACE}/req#openWorkitemIdentifier={item["id"]}'
    record['customFieldValues']=[x for x in live.get('customFieldValues',[]) if str(x.get('fieldId')) in ['79','80','101586','101587','sumActualLaborHour','sumPlanedLaborHour']]
    record['comment_id']=found[0].get('id');record['body_format']=live.get('formatType')
    record['body_verified']=True
    result[key]=record
(HERE/'final-readback.sanitized.json').write_text(json.dumps(result,ensure_ascii=False,indent=2))
print(json.dumps({k:{'ticket':x['serialNumber'],'owner':x['assignedTo']['name'],'status':x['status']['name'],'body_verified':True,'comment_readback':bool(x['comment_id'])} for k,x in result.items()},ensure_ascii=False))
