"""validate-tasks-03 — 셸 시나리오에서 꺼낸 단언 블록.

호출부: validators/lib/validate-tasks.sh:36
규칙 R1 은 실행될 소스를 문자열/heredoc 이 아니라 실파일에 두게 한다.
이 파일의 내용은 꺼내기 전과 같다 — 옮기기만 했다.
"""
from pathlib import Path
import json
import sys

project_root = Path(sys.argv[1])
discovery_path = Path(sys.argv[2])
expected_task_key = sys.argv[3]
expected_task_manifest_relative_path = sys.argv[4]
expected_reference_relative_path = sys.argv[5]
expected_task_catalog_relative_path = sys.argv[6]
errors = []

if not discovery_path.is_file():
    errors.append(f"latest-task discovery file is missing: {discovery_path}")
else:
    discovery = json.loads(discovery_path.read_text())

    if discovery.get("taskKey") != expected_task_key:
        errors.append("latest-task discovery does not point to the expected task key")

    if discovery.get("taskManifestPath") != expected_task_manifest_relative_path:
        errors.append("latest-task discovery does not point to the expected task manifest")

    if discovery.get("referenceExpectationsPath") != expected_reference_relative_path:
        errors.append("latest-task discovery does not expose the expected reference expectations path")

    if discovery.get("taskCatalogPath") != expected_task_catalog_relative_path:
        errors.append("latest-task discovery does not expose taskCatalogPath")

    latest_run_prompts_relative_path = discovery.get("latestRunPromptsPath", "")
    if not latest_run_prompts_relative_path:
        errors.append("latest-task discovery is missing latestRunPromptsPath")

    latest_run_manifest_relative_path = discovery.get("latestRunManifestPath", "")
    if not latest_run_manifest_relative_path:
        errors.append("latest-task discovery is missing latestRunManifestPath")
    else:
        latest_run_manifest_path = project_root / latest_run_manifest_relative_path
        if not latest_run_manifest_path.is_file():
            errors.append(f"latest run manifest is missing: {latest_run_manifest_path}")
        else:
            run_manifest = json.loads(latest_run_manifest_path.read_text())
            if (
                latest_run_prompts_relative_path
                and run_manifest.get("workerPromptsDirectoryPath")
                != latest_run_prompts_relative_path
            ):
                errors.append(
                    "latest-task discovery latestRunPromptsPath does not match the latest run manifest"
                )

if errors:
    for error in errors:
        print(error, file=sys.stderr)
    sys.exit(1)
