# -*- coding: utf-8 -*-
"""Update final review evidence after expanded regression testing."""
import json
from datetime import datetime
from zoneinfo import ZoneInfo
from pathlib import Path
from transport import api, PREFIX, ORG

HERE = Path(__file__).resolve().parent
STATE = json.loads((HERE / 'items.sanitized.json').read_text())
ASSIGNEE = '635755195dc8531eeb2e33d9'
LATEST_COMMIT = '030d2276d0f57e24cdf9bfab4cdf52224e933aa4'
MR_URL = 'https://codeup.aliyun.com/60069db88deaa14d9e02b875/zhct/store/change/980'
TZ = ZoneInfo('Asia/Shanghai')

def millis(text):
    return int(datetime.fromisoformat(text).replace(tzinfo=TZ).timestamp() * 1000)

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

validation_id = STATE['tasks']['validation']['id']
effort_path = PREFIX + '/workitems/' + validation_id + '/effortRecords'
rows = as_list(api('GET', effort_path))
matches = [row for row in rows if 'VWCG1450-ACTUAL-VALIDATION' in str(row.get('description', ''))]
if len(matches) != 1:
    raise RuntimeError('Validation effort missing or duplicated')
record = matches[0]
api('PUT', effort_path + '/' + record['id'], {
    'operatorId': ASSIGNEE,
    'actualTime': 0.4,
    'gmtStart': millis('2026-10-19T09:57:00'),
    'gmtEnd': millis('2026-10-19T10:16:00'),
    'description': 'VWCG1450-ACTUAL-VALIDATION 自动化测试、参数契约、生产构建、页面验收、Codeup和云效收尾；追加全量前端单测和全选后手工改单组合回归。按真实AI辅助执行时间登记，包含方案/分析时间，不含用户等待。',
})

detail = '''追加组合回归与自审修正：
- 新增验证“全选后手工取消具体部门，不会重新触发全选”，并覆盖禁用部门、空值序列化和两个筛选器隔离。
- 全量前端业务单测：11 suites / 49 tests 全部通过。
- 目标及相邻消费订单测试：3 suites / 14 tests 全部通过。
- 快捷操作改为禁用伪节点并隐藏复选框，只响应文字行点击，内部标识请求前二次剔除。
- 追加提交：030d2276d0f57e24cdf9bfab4cdf52224e933aa4（#VWCG-1452 补充部门筛选组合回归测试）。
- MR：''' + MR_URL + '''，ahead=2、behind=0、NO_CONFLICT、allRequirementsPass=true。
- 默认全仓 Jest 会误收集 build/test.js 并报“无测试”，同时宿主机Node22触发旧Webpack兼容错误；真实 test/unit/specs 目录已全部通过，生产构建使用项目标准Node14容器通过。'''

def ensure_comment(item_id, marker):
    path = PREFIX + '/workitems/' + item_id + '/comments'
    rows = as_list(api('GET', path))
    matches = [row for row in rows if marker in str(row.get('content', row.get('comment', '')))]
    if not matches:
        api('POST', path, {'content': marker + '\n' + detail})
    rows = as_list(api('GET', path))
    matches = [row for row in rows if marker in str(row.get('content', row.get('comment', '')))]
    if len(matches) != 1:
        raise RuntimeError('Follow-up comment readback failed')
    return matches[0].get('id')

comment_ids = {
    'parent': ensure_comment(STATE['parent']['id'], 'VWCG1450-POST-REVIEW'),
    'development': ensure_comment(STATE['tasks']['development']['id'], 'VWCG1450-POST-REVIEW'),
    'validation': ensure_comment(validation_id, 'VWCG1450-POST-REVIEW'),
}
mr = api('GET', f'/oapi/v1/codeup/organizations/{ORG}/repositories/4913137/changeRequests/980')
if mr.get('ahead') != 2 or mr.get('behind') != 0 or not mr.get('allRequirementsPass'):
    raise RuntimeError('MR readback mismatch')
parent = api('GET', PREFIX + '/workitems/VWCG-1450')
development = api('GET', PREFIX + '/workitems/' + STATE['tasks']['development']['serialNumber'])
validation = api('GET', PREFIX + '/workitems/' + STATE['tasks']['validation']['serialNumber'])
rows = as_list(api('GET', effort_path))
record = next(row for row in rows if 'VWCG1450-ACTUAL-VALIDATION' in str(row.get('description', '')))
result = {
    'statuses': {
        'parent': parent.get('status'),
        'development': development.get('status'),
        'validation': validation.get('status'),
    },
    'actualEffort': {
        'development': 0.6,
        'validation': record.get('actualTime'),
        'total': 1.0,
    },
    'latestCommit': LATEST_COMMIT,
    'mr': {key: mr.get(key) for key in ['localId', 'title', 'sourceBranch', 'targetBranch', 'status', 'ahead', 'behind', 'conflictCheckStatus', 'allRequirementsPass', 'detailUrl']},
    'commentIds': comment_ids,
}
(HERE / 'post-review-readback.sanitized.json').write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(result, ensure_ascii=False, indent=2))
