"""Generic fixture orchestration using the selected engine's build profile."""
from pathlib import Path
import os
import platform
import shutil
from .process import run
from .project import digest, parse, read
from .results import SDKError
from .compiler_diagnostics import parse as parse_compiler_diagnostics


BACKEND_SCHEMA = "pcfc11.backend/1"


def pcfc11_backend(executable, profile, *, timeout, cancel):
    if profile.get("pcfc11_backend_identity") != BACKEND_SCHEMA:
        raise SDKError("SDK_BACKEND_CAPABILITY",
                       "Select PyCForge 1.3.85 or a compatible engine for PCFC11 backend verification, or select GCC directly.",
                       status="incomplete")
    targets = [arg for arg in (*profile["compile_args"], *profile["link_args"]) if arg.startswith("--target=")]
    probe = run([executable, "--backend-json", *targets], timeout=timeout, cancel=cancel, max_output=64*1024)
    if probe.returncode:
        raise SDKError("SDK_BACKEND_CAPABILITY", "This PCFC11 driver cannot report its backend. Use PCFC11 0.2.32 or a compatible release, or select GCC directly.", status="incomplete")
    try:
        reply = parse(probe.stdout)
    except SDKError as exc:
        raise SDKError("SDK_COMPILER_BACKEND", "PCFC11 returned an invalid backend identity.", status="incomplete") from exc
    if (not isinstance(reply, dict) or reply.get("schema") != BACKEND_SCHEMA
            or reply.get("target") != "x86_64-linux-gnu" or reply.get("environment") != "PCFC11_LINUX_CC"):
        raise SDKError("SDK_BACKEND_CAPABILITY", "Unsupported PCFC11 backend identity or native target.", status="incomplete")
    command = reply.get("command")
    if not isinstance(command, str) or not command or len(command) > 4096 or "\0" in command:
        raise SDKError("SDK_COMPILER_BACKEND", "PCFC11 reported an invalid backend command.", status="incomplete")
    found = shutil.which(command)
    if not found:
        raise SDKError("SDK_COMPILER_BACKEND", f"PCFC11 backend {command!r} is missing or is not executable. Restore or select GCC and run Verify fixtures.",
                       status="incomplete", details={"command": command})
    invocation = Path(found).absolute()
    try:
        resolved = invocation.resolve(strict=True)
        recursive = resolved.samefile(executable)
        binary = read(resolved, 128*1024*1024)
    except (OSError, RuntimeError, SDKError) as exc:
        raise SDKError("SDK_COMPILER_BACKEND", f"Cannot fingerprint PCFC11 backend {command!r}. Check the file and run Verify fixtures.",
                       status="incomplete", details={"command": command}) from exc
    if recursive:
        raise SDKError("SDK_COMPILER_BACKEND", "PCFC11 cannot use itself as its GCC backend. Select GCC and run Verify fixtures.", status="incomplete")
    return {"schema": BACKEND_SCHEMA, "target": reply["target"], "command": command,
            "executable": str(invocation), "resolved": str(resolved), "sha256": digest(binary)}


def compiler_identity(compiler, profile, *, timeout, cancel):
    if type(profile) is not dict or platform.system() not in profile.get("hosts", []):
        raise SDKError("SDK_TARGET", "Native verification is not qualified for this host by the selected engine profile.")
    for key in ("compile_args", "link_args", "compiler_version_args"):
        if type(profile.get(key)) is not list or any(type(a) is not str or len(a) > 4096 for a in profile[key]):
            raise SDKError("SDK_CAPABILITY", "Malformed native toolchain profile.")
    executable = shutil.which(str(compiler))
    if not executable:
        raise SDKError("SDK_COMPILER", "C compiler not found: " + str(compiler), status="incomplete")
    executable = str(Path(executable).resolve())
    binary = read(executable, 128*1024*1024)
    result = run([executable, *profile["compiler_version_args"]], timeout=timeout, cancel=cancel)
    if result.returncode:
        raise SDKError("SDK_COMPILER", "Cannot identify the selected C compiler.", status="incomplete")
    version = result.stdout.decode("utf-8", "replace")
    identity = {"executable": executable, "sha256": digest(binary), "version": version,
                "system": platform.system(), "machine": platform.machine(), "profile": profile}
    if version.startswith("PCFC11 "):
        identity["backend"] = pcfc11_backend(executable, profile, timeout=timeout, cancel=cancel)
        targets = [arg for arg in (*profile["compile_args"], *profile["link_args"]) if arg.startswith("--target=")]
        probe = run([executable, "--info-json", *targets], timeout=timeout, cancel=cancel, max_output=64*1024)
        try:
            info = parse(probe.stdout)
        except SDKError as exc:
            raise SDKError("SDK_COMPILER_DIAGNOSTICS", "Cannot read PCFC11's diagnostic capability. Check the selected compiler.", status="incomplete") from exc
        if (probe.returncode or type(info) is not dict or info.get("name") != "PCFC11"
                or type(info.get("schema")) is not int or info["schema"] != 1
                or type(info.get("process_api")) is not int or info["process_api"] != 1
                or info.get("target") != "x86_64-linux-gnu" or info.get("diagnostics_json") is not True):
            raise SDKError("SDK_COMPILER_DIAGNOSTICS", "PCFC11 does not report the supported JSON diagnostic interface.", status="incomplete")
        if (type(info.get("version")) is not str or not version.startswith("PCFC11 " + info["version"] + " ")
                or type(info.get("error_codes", 0)) is not int or not 0 <= info.get("error_codes", 0) < 2**31):
            raise SDKError("SDK_COMPILER_DIAGNOSTICS", "PCFC11 returned inconsistent diagnostic identity metadata.", status="incomplete")
        identity["diagnostics"] = {"format": "pcfc11-jsonl/1", "error_codes": info.get("error_codes", 0)}
    return identity


def check_compiler(recorded, selected, profile, *, timeout, cancel):
    current = compiler_identity(selected or recorded.get("executable", ""), profile, timeout=timeout, cancel=cancel)
    if current != recorded:
        if recorded.get("backend") != current.get("backend"):
            raise SDKError("SDK_STALE_COMPILER", "The PCFC11 backend identity changed. Run Verify fixtures with the selected GCC before packaging.",
                           details={"recorded_backend": recorded.get("backend"), "current_backend": current.get("backend")})
        raise SDKError("SDK_STALE_COMPILER", "The recorded compiler or target profile changed. Run Verify fixtures.")


def execute_fixture(c_text, expected, compiler, work, *, timeout, cancel):
    source, executable = Path(work)/"program.c", Path(work)/"program"
    source.write_text(c_text, encoding="utf-8", newline="\n")
    profile = compiler["profile"]
    env = None
    if "backend" in compiler:
        env = dict(os.environ, PCFC11_LINUX_CC=compiler["backend"]["executable"])
    structured = compiler.get("diagnostics", {}).get("format") == "pcfc11-jsonl/1"
    diagnostic_args = ["--diagnostics-json"] if structured else []
    build = run([compiler["executable"], *diagnostic_args, *profile["compile_args"], str(source), *profile["link_args"], "-o", str(executable)],
                cwd=work, env=env, timeout=timeout, cancel=cancel)
    invalid_encoding = False
    try:
        stderr = build.stderr.decode("utf-8")
    except UnicodeError:
        stderr = build.stderr.decode("utf-8", "replace")
        invalid_encoding = structured
    diagnostics = parse_compiler_diagnostics(stderr, requested=structured)
    if invalid_encoding:
        diagnostics['status'] = 'incomplete'
        diagnostics['issues'].append({'reason': 'invalid-utf8'})
    result = {"compiler_exit_code": build.returncode, "compiler_stderr": stderr,
              "compiler_diagnostics": diagnostics,
              "compiler_source": {"file": str(source), "sha256": digest(c_text.encode("utf-8"))}}
    if diagnostics["status"] == "incomplete":
        return {**result, "passed": False, "reason": "Structured compiler diagnostics are incomplete; native execution was not attempted."}
    if any(d["severity"] == "error" for d in diagnostics["items"]):
        return {**result, "passed": False, "reason": "The compiler reported an error; native execution was not attempted."}
    if build.returncode or not executable.is_file():
        return {**result, "passed": False, "reason": "Native compilation did not produce an executable."}
    native = run([executable], cwd=work, timeout=timeout, cancel=cancel)
    actual = {"stdout": native.stdout.decode("utf-8", "replace"), "stderr": native.stderr.decode("utf-8", "replace"), "exit_code": native.returncode}
    output_identity = {}
    for field in ('stdout', 'stderr'):
        content = getattr(native, field)
        try: content.decode('utf-8'); valid_utf8 = True
        except UnicodeError: valid_utf8 = False
        output_identity[field] = {'sha256':digest(content), 'bytes':len(content), 'valid_utf8':valid_utf8}
        if not valid_utf8: output_identity[field]['hex_prefix'] = content[:128].hex()
    passed = (native.stdout == expected["stdout"].encode("utf-8") and native.stderr == expected["stderr"].encode("utf-8")
              and native.returncode == expected["exit_code"])
    return {**result, "actual": actual, "output_identity":output_identity, "passed": passed,
            "reason": "Fixture matched." if passed else "Native result differs from the fixture expectation."}
