#!/usr/bin/env python3
"""Update only the school S05 waste scenario without rewriting the full suite.

This focused synchronizer deliberately leaves S00-S04 and S06-S14 untouched.
The main S05 regression keeps the rows created by Apifox so MySQL
``foodsafe_test`` and DM ``WWWWEB`` can be verified directly afterwards.
"""

from __future__ import annotations

import copy
import importlib.util
from pathlib import Path


HERE = Path(__file__).resolve().parent
BASE_SCRIPT = HERE / "sync_school_s00_s06_scenarios.py"
SCENARIO_NAME = "S05-废弃物管理（双库真实写入）"


def load_base():
    spec = importlib.util.spec_from_file_location("school_s00_s06", BASE_SCRIPT)
    if spec is None or spec.loader is None:
        raise RuntimeError(f"Unable to load {BASE_SCRIPT}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def main() -> None:
    base = load_base()
    api = base.Apifox()
    by_name = {item["name"]: item for item in api.scenarios()}
    target = by_name.get(SCENARIO_NAME)
    source = by_name.get("S00-环境与认证（双库）")
    if target is None or source is None:
        raise RuntimeError("S00 or S05 scenario is missing")

    target_data = api.scenario(int(target["id"]))
    source_data = api.scenario(int(source["id"]))
    loop_template = source_data["steps"][0]
    login_template = loop_template["children"][0]
    request_template = loop_template["children"][1]
    config = base.SCENARIOS[SCENARIO_NAME]

    target_data["description"] = config["description"]
    target_data["folderId"] = base.FOLDER_ID
    loop = copy.deepcopy(loop_template)
    loop["id"] = base.new_id()
    loop["number"] = 1
    loop["children"] = [base.make_login(login_template, config["prefix"])]
    for number, raw_operation in enumerate(config["operations"], start=2):
        operation = base.normalized_operation(raw_operation)
        step = base.make_request(request_template, **operation)
        step["number"] = number
        loop["children"].append(step)
    target_data["steps"] = [loop]
    api.save(target_data)

    saved = api.scenario(int(target["id"]))
    requests = base.flatten_requests(saved["steps"])
    business = [item for item in requests if item.get("path") != "{{base_url}}/auth/login"]
    if len(business) != len(config["operations"]):
        raise RuntimeError(f"Expected {len(config['operations'])} business requests, got {len(business)}")
    if not all(base.request_has_auditable_evidence(request) for request in requests):
        raise RuntimeError("One or more S05 requests lack APIFOX_EVIDENCE")

    delete_steps = [
        child
        for child in saved["steps"][0]["children"]
        if child.get("customHttpRequest", {}).get("method", "").upper() == "DELETE"
    ]
    if len(delete_steps) != 2 or not all(step.get("disable") is True for step in delete_steps):
        raise RuntimeError("S05 main regression must keep both DELETE steps disabled")

    suite = api.test_suite()
    linked_ids = [int(item["testScenarios"][0]["id"]) for item in suite.get("items", [])]
    if int(target["id"]) not in linked_ids:
        raise RuntimeError("S05 is not linked by the one-click suite")
    print(
        f"{SCENARIO_NAME}: id={target['id']}, businessRequests={len(business)}, "
        f"enabledBusiness={sum(1 for step in saved['steps'][0]['children'][1:] if not step.get('disable'))}, "
        f"deleteStepsDisabled={len(delete_steps)}, suiteItems={len(linked_ids)}"
    )


if __name__ == "__main__":
    main()
