"""SDK application inputs and controller-owned evaluation reports."""

from __future__ import annotations

import json
import os
import shlex
from pathlib import Path
from typing import Any


def application_eval_context() -> dict[str, Any] | None:
    raw = os.environ.get("COMET_APPLICATION_EVAL_CONTEXT")
    if not raw:
        return None
    value = json.loads(raw)
    if not isinstance(value, dict) or not isinstance(value.get("preview"), dict):
        raise ValueError("Invalid SDK application Eval context")
    skill = Path(value["skillRoot"]).resolve()
    preview = json.loads((skill / "references/workflows.json").read_text(encoding="utf-8"))
    if preview != value["preview"]:
        raise ValueError("SDK application Eval context does not match its frozen snapshot")
    return value


def application_environment(skill_root: Path) -> Path | None:
    if not (skill_root / "scripts/application/application.json").is_file():
        return None
    from scaffold.python.paths import EVAL_ROOT

    return EVAL_ROOT / "scaffold/environments/workflow-application"


def application_generation_guidance(snapshot) -> str:
    if not any(item.path == "references/workflows.json" for item in snapshot.files):
        return ""
    return """
This is a complete SDK workflow application, not a prose-only Skill. Read the workflow definitions,
input/output schemas, fixed dependencies, approval choices and recovery contracts in the snapshot.
Generate a normal execution case plus cases for relevant rejection, invalid-input and recovery paths.
Every case must start or resume an actual SDK Run; an invalid-input case can first create a valid Run
and then check rejection of an invalid action. Check real business artifacts using deterministic
expectations. Do not substitute a hand-written state file for Runtime execution. Explain the required
scenario in each prompt; do not claim coverage of paths that were not executed. Use only /workspace
and isolated fixtures. Mock external services; never send real messages, publish or push remotely.
The controller installs the application and its fixed dependency Skills before execution. Use the
installed application Skill or comet runtime dispatch --application <application id>. Read the
actual immutable package selected by that installed entry; do not invent another workflow.
Each case already has its own isolated /workspace. This is the application project root, not a nested project directory.
Always use --project-root /workspace for Runtime commands, and keep the current fixed application id.
Do not create /workspace/eval-grill-normal or another per-case project root; do not cd into a new project
and run the SDK there. Business source subdirectories may exist inside /workspace, but they do not change
the application project root. Do not generate or install another application or copy a replacement workflow.
Use workspace-relative expectation paths such as CONTEXT.md and src/calculator.py, not /workspace/CONTEXT.md
or /workspace/eval-grill-normal/CONTEXT.md. Do not create fake Run, Action, Wait or approval state to satisfy
an expectation. The controller checks actual Runtime execution separately from business artifact assertions.
"""


def install_application_for_case(test_dir: Path, package: str, agent: str) -> str:
    context = application_eval_context()
    if context is None:
        return ""
    from scaffold.python.utils import run_command_in_docker
    import shlex

    platform = {"claude-code": "claude", "codex": "codex", "qoder": "qoder", "codebuddy": "codebuddy"}.get(agent)
    if platform is None:
        raise ValueError("SDK application Eval needs a registered installation platform for this Agent")
    command = "comet application distribute " + shlex.quote(package + "/scripts/application/application.json") + " --project /workspace --platform " + platform + " --json"
    preview_result = run_command_in_docker(test_dir, command, 120)
    preview = json.loads(preview_result.stdout)
    if preview_result.returncode != 0 or preview.get("contentHash") != context["preview"]["application"]["contentHash"]:
        raise ValueError("SDK application installation preview did not match the fixed candidate")
    installed_result = run_command_in_docker(test_dir, command + " --confirmation-hash " + shlex.quote(preview["confirmationHash"]), 120)
    if installed_result.returncode != 0:
        raise ValueError("SDK application installation failed before model execution")
    installed = json.loads(installed_result.stdout)
    expected = "/workspace/.comet/applications/" + context["preview"]["application"]["id"] + "/versions/" + context["preview"]["application"]["contentHash"] + "/application.json"
    if installed.get("file") != expected:
        raise ValueError("SDK application installation selected another immutable package")
    return expected


def application_execution_prompt(prompt: str, package: str, file: str) -> str:
    context = application_eval_context()
    if context is None:
        return prompt
    return (
        "[SDK application evaluation]\nThe controller installed the actual " + context["preview"]["application"]["id"]
        + " application Skill and its fixed dependencies. Load that Skill and follow its Runtime instructions. "
        + "The immutable application file is " + file + ". The original workflow definitions and contracts are in "
        + package + "/references/workflows.json. Keep actual Run/Action/Wait identities; do not create a replacement workflow or fabricate state.\n\n"
        + prompt
    )


def application_runs_validator(test_dir: Path, outputs: dict) -> tuple[list[str], list[str]]:
    context = application_eval_context()
    if context is None:
        return [], []
    from scaffold.python.utils import run_command_in_docker

    identity = context["preview"]["application"]
    package = outputs.get("skill_package_path")
    if not isinstance(package, str) or not package:
        return [], ["SDK application package snapshot is unavailable"]
    passed: list[str] = []
    failed: list[str] = []
    observed: set[str] = set()
    executed: set[str] = set()
    choices: set[str] = set()
    recovered: set[str] = set()
    discovery = (
        "import { listWorkflowApplicationRunRecords } from '@rpamis/comet/applications';"
        "console.log(JSON.stringify(await listWorkflowApplicationRunRecords('/workspace')));"
    )
    try:
        listed = run_command_in_docker(test_dir, "node --input-type=module -e " + shlex.quote(discovery), 60)
        runs = json.loads(listed.stdout)
        if listed.returncode != 0 or not isinstance(runs, list):
            raise ValueError("Runtime Run discovery failed")
    except (OSError, ValueError, TypeError) as exc:
        runs = []
        failed.append("SDK Run discovery rejected: " + str(exc))
    for record in runs:
        try:
            if not isinstance(record, dict):
                raise ValueError("Runtime Run discovery returned an invalid record")
            if record.get("applicationId") != identity["id"]:
                continue
            if record.get("error") or record.get("record") is None:
                raise ValueError("Runtime rejected the saved application Run")
            run_id = record.get("runId")
            if not isinstance(run_id, str) or not run_id:
                raise ValueError("Runtime Run discovery returned an invalid Run ID")
            request = test_dir / ".eval-sdk-inspect.json"
            request.write_text(json.dumps({"operation": "inspect", "runId": run_id}), encoding="utf-8")

            command = (
                "comet runtime dispatch --application "
                + shlex.quote(identity["id"])
                + " --project-root /workspace --request .eval-sdk-inspect.json --details --json"
            )
            actual = run_command_in_docker(test_dir, command, 60)
            result = json.loads(actual.stdout)
            if actual.returncode != 0 or result.get("status") != "succeeded":
                raise ValueError("Runtime inspection rejected the Run")
            run = result["data"]
            if result["application"]["id"] != identity["id"] or result["application"]["version"] != identity["version"]:
                raise ValueError("Run belongs to another application version")
            if result["application"]["contentHash"] != context["preview"]["runtimeIdentityHash"]:
                raise ValueError("Application implementation or fixed dependencies changed inside the evaluation")
            expected = next((workflow for workflow in context["preview"]["workflows"] if workflow["id"] == run["workflow"]["id"]), None)
            if expected is None or expected["definitionHash"] != run["workflow"]["hash"]:
                raise ValueError("Actual SDK Run uses another workflow definition")
            for action in run["actions"]:
                if action["status"] == "succeeded":
                    observed.add(run["workflow"]["id"] + "/" + action["stepId"])
                    executed.add(run["workflow"]["id"] + "/" + action["stepId"])
                    if action["attempt"] > 1:
                        recovered.add(run["workflow"]["id"] + "/" + action["stepId"])
            for wait in run["waits"]:
                observed.add(run["workflow"]["id"] + "/" + wait["stepId"])
                if wait.get("decision"):
                    executed.add(run["workflow"]["id"] + "/" + wait["stepId"])
                    choices.add(run["workflow"]["id"] + "/" + wait["stepId"] + "/" + wait["decision"]["choice"])
            passed.append("SDK Run inspected by actual Runtime: " + run_id)
        except (OSError, ValueError, KeyError, TypeError) as exc:
            failed.append("SDK Run evidence rejected: " + str(exc))
    if not passed:
        failed.append("No actual SDK application Run was verified")
    outputs["application_coverage"] = sorted(observed)
    outputs["application_executed_steps"] = sorted(executed)
    outputs["application_choices"] = sorted(choices)
    outputs["application_recovery"] = sorted(recovered)
    return passed, failed


def _application_completeness(logger, context, results):
    """核对固定用例、收集矩阵和持久化报告，缺失证据不能证明完整执行。"""
    import hashlib
    from collections import Counter

    import yaml

    from scaffold.python.aligned_comparison import load_expected_case_matrix
    from scaffold.python.evidence import stable_treatment_name

    def unlinked_path(value):
        path = Path(os.path.abspath(value))
        if any(part.is_symlink() for part in (path, *path.parents)):
            raise ValueError("evidence path contains a symbolic link")
        return path

    failures = []
    loaded = load_expected_case_matrix(logger.base_dir)
    if loaded.matrix is None:
        return ["Expected case matrix unavailable: " + (loaded.error or "missing")], None
    matrix = loaded.matrix
    metadata = getattr(logger, "metadata", {}).get("expected_case_matrix")
    if metadata is not None and metadata != {
        "schema": "comet.eval.expected-case-matrix.v1",
        "matrix_hash": matrix.matrix_hash,
        "case_count": len(matrix.cases),
        "path": "expected-case-matrix.json",
    }:
        failures.append("Expected case matrix metadata does not match its persisted evidence")
    expected = {(case.task, case.treatment, case.rep) for case in matrix.cases}
    names = sorted(case.task for case in matrix.cases)
    if not 2 <= len(names) <= 4 or len(set(names)) != len(names):
        failures.append("Expected case matrix must contain 2–4 distinct application tasks")

    task_set = getattr(logger, "metadata", {}).get("application_task_set")
    receipt_path = logger.base_dir / "application-task-set.json"
    try:
        unlinked_path(receipt_path)
        if receipt_path.exists():
            if not receipt_path.is_file():
                raise ValueError("collection receipt is not a regular file")
            receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
            if (
                receipt.get("schema") != "comet.workflow.application.eval.task-set.v1"
                or receipt.get("experimentId") != context["experimentId"]
                or receipt.get("confirmationHash") != context["preview"]["confirmationHash"]
                or receipt.get("snapshotHash") != context["snapshotHash"]
                or receipt.get("matrixHash") != matrix.matrix_hash
                or (task_set is not None and receipt.get("taskSet") != task_set)
            ):
                raise ValueError("collection receipt identity does not match")
            task_set = receipt.get("taskSet")
        frozen = context["preview"].get("taskSet")
        if frozen is not None:
            if task_set is not None and task_set != frozen:
                raise ValueError("task set differs from the confirmed preview")
            task_set = frozen
        if not isinstance(task_set, dict):
            raise ValueError("fixed task set is missing")
        generated_root = unlinked_path(Path(context["projectRoot"]) / ".comet/eval/generated")
        manifest_path = unlinked_path(task_set["manifestPath"])
        manifest_path.relative_to(generated_root)
        if not manifest_path.is_file():
            raise ValueError("fixed manifest is not a regular file")
        manifest_bytes = manifest_path.read_bytes()
        if task_set.get("manifestHash") != "sha256:" + hashlib.sha256(manifest_bytes).hexdigest():
            raise ValueError("fixed manifest hash does not match")
        manifest = yaml.safe_load(manifest_bytes)
        tasks = manifest["evaluation"]["tasks"]
        if not isinstance(tasks, list) or sorted(task["name"] for task in tasks) != names:
            raise ValueError("fixed manifest tasks do not match the complete matrix")
    except (OSError, ValueError, TypeError, KeyError, AttributeError, yaml.YAMLError) as error:
        failures.append("Application task set rejected: " + str(error))

    def identity(name, events, rep):
        from scaffold.python.evidence_contract import case_identity
        parsed = case_identity({"name": name, "rep": rep, "passed": True,
                                "events_summary": events}, context["experimentId"])
        return parsed["task"], parsed["treatment"], parsed["repetition"]

    observed = []
    result_payloads = Counter()
    for result in results:
        try:
            key = identity(result.name, result.events_summary, result.events_summary.get("sample"))
            observed.append(key)
            result_payloads[json.dumps({"name": result.name, "passed": result.passed,
                "checks_passed": result.checks_passed, "checks_failed": result.checks_failed,
                "events_summary": result.events_summary}, sort_keys=True)] += 1
        except (ValueError, TypeError, AttributeError) as error:
            failures.append("Application result identity rejected: " + str(error))
    if len(observed) != len(set(observed)):
        failures.append("Application results contain duplicate cases")
    missing, extra = expected - set(observed), set(observed) - expected
    if missing:
        failures.append("Missing application cases: " + repr(sorted(missing)))
    if extra:
        failures.append("Unexpected application cases: " + repr(sorted(extra)))

    persisted = []
    report_payloads = Counter()
    try:
        reports_root = unlinked_path(logger.base_dir / "reports")
        if not reports_root.is_dir():
            raise ValueError("reports directory is missing or invalid")
        report_paths = sorted(reports_root.glob("*.json"))
    except (OSError, ValueError) as error:
        failures.append("Application reports directory rejected: " + str(error))
        report_paths = []
    for path in report_paths:
        try:
            unlinked_path(path)
            if not path.is_file():
                raise ValueError("report is not a regular file")
            report = json.loads(path.read_text(encoding="utf-8"))
            from scaffold.python.evidence_contract import case_identity
            case_identity(report, context["experimentId"])
            key = identity(report["name"], report["events_summary"], report["rep"])
            if path.name != f"{stable_treatment_name(report['name'])}_rep{report['rep']}_report.json":
                raise ValueError("report filename does not match its identity")
            if type(report["passed"]) is not bool:
                raise ValueError("report passed must be a boolean")
            quality = report.get("sample_quality", report["events_summary"].get("sample_quality"))
            if not isinstance(quality, dict) or quality.get("status") != "included":
                raise ValueError("report sample quality is not included")
            persisted.append(key)
            report_payloads[json.dumps({field: report[field] for field in (
                "name", "passed", "checks_passed", "checks_failed", "events_summary"
            )}, sort_keys=True)] += 1
        except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
            failures.append(f"Application report rejected ({path.name}): {error}")
    if len(persisted) != len(set(persisted)) or set(persisted) != expected:
        failures.append("Persisted application reports do not match the complete case matrix")
    if report_payloads != result_payloads:
        failures.append("Persisted application reports do not match the aggregated results")
    return failures, task_set


def write_application_result(logger) -> None:
    context = application_eval_context()
    if context is None:
        return
    results = [result for runs in logger.results.values() for result in runs]
    names = sorted({result.events_summary.get("task", "") for result in results} - {""})
    preview = context["preview"]
    from scaffold.python.case_selection import read_case_selection
    selection = read_case_selection()
    covered = {step for result in results for step in result.events_summary.get("application_coverage", [])}
    executed = {step for result in results for step in result.events_summary.get("application_executed_steps", [])}
    covered_choices = {choice for result in results for choice in result.events_summary.get("application_choices", [])}
    declared_choices = {workflow["id"] + "/" + step + "/" + choice for workflow in preview["workflows"] for step, spec in workflow.get("definition", {}).get("steps", {}).items() for choice in spec.get("choices", [])}
    declared = {workflow["id"] + "/" + step for workflow in preview["workflows"] for step in workflow["steps"]}
    failures = [check for result in results for check in result.checks_failed]
    completeness_failures, task_set = _application_completeness(logger, context, results)
    failures.extend(completeness_failures)
    complete = not completeness_failures
    verified = all(any(check.startswith("SDK Run inspected by actual Runtime:") for check in result.checks_passed) for result in results)
    if not executed:
        verified = False
        failures.append("No SDK workflow step or decision was actually executed")
    clean = all(result.events_summary.get("sample_quality", {}).get("status", "included") == "included" for result in results)
    exitstatus = getattr(logger, "metadata", {}).get("pytest_exitstatus", 0)
    harness_complete = exitstatus in {0, 1} and not (exitstatus == 1 and all(result.passed for result in results)) and not getattr(logger, "metadata", {}).get("pytest_errors", 0)
    status = "passed" if complete and clean and verified and harness_complete and all(result.passed for result in results) else "failed" if complete and clean and verified and harness_complete else "incomplete"
    if selection is not None:
        status = "incomplete"
    models = set()
    for case in results:
        reported = case.events_summary.get("model_usage") or {}
        if isinstance(reported, dict) and reported:
            models.update(name for name in reported if isinstance(name, str) and name)
        else:
            selected = (case.events_summary.get("execution_identity") or {}).get("model")
            if selected:
                models.add(str(selected))
    costs = [case.total_cost_usd for case in results]
    known_cost = sum(cost for cost in costs if cost is not None)
    result = {
        "schema": "comet.workflow.application.eval.result.v1",
        "experimentId": context["experimentId"],
        "confirmationHash": preview["confirmationHash"],
        "snapshotHash": context["snapshotHash"],
        "application": preview["application"],
        "settings": preview["settings"],
        "status": status,
        **({"caseSelection": {"sourceRunId": selection["sourceRunId"]}} if selection else {}),
        "taskNames": names,
        "passed": sum(result.passed for result in results),
        "total": len(results),
        "report": "summary.html" if (logger.base_dir / "summary.html").is_file() else "summary.md",
        "limitations": [*preview["limitations"], "Uncovered SDK steps: " + ", ".join(sorted(declared - covered)), "Uncovered decisions: " + ", ".join(sorted(declared_choices - covered_choices))],
        "failures": failures,
        "coveredSteps": sorted(covered),
        "executedSteps": sorted(executed),
        "uncoveredSteps": sorted(declared - covered),
        "coveredChoices": sorted(covered_choices),
        "uncoveredChoices": sorted(declared_choices - covered_choices),
        "recoveredActions": sorted({step for result in results for step in result.events_summary.get("application_recovery", [])}),
        "actualModels": sorted(models),
        "modelIdentityAvailable": bool(models),
        "caseCostUsd": known_cost if costs and all(cost is not None for cost in costs) else None,
        "knownCaseCostUsd": known_cost if any(cost is not None for cost in costs) else None,
        "costUsd": None,
        "costStatus": "case-costs-only" if costs and all(cost is not None for cost in costs) else "partial" if any(cost is not None for cost in costs) else "unavailable",
        **({"taskSet": task_set} if task_set else {}),
    }
    # The output location is selected by the same controller-owned experiment identity.
    target = logger.base_dir / "application-result.json"
    if target.resolve() != Path(context["resultFile"]).resolve():
        raise ValueError("SDK application report is outside the selected experiment")
    from scaffold.python.logging import _atomic_write_json

    _atomic_write_json(target, result)
