#!/usr/bin/env python3
"""Contract test for executable Vibium compatibility and CARBON extensions."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
LAUNCHER = PLUGIN / "bin" / "carbon-runtime"


def run(*args: str, ok: bool = True) -> subprocess.CompletedProcess[str]:
    result = subprocess.run(
        [str(LAUNCHER), "vibium", *args], text=True, capture_output=True, check=False
    )
    if ok and result.returncode:
        raise AssertionError(f"carbon-runtime vibium {' '.join(args)} failed:\n{result.stderr}")
    if not ok and not result.returncode:
        raise AssertionError(f"carbon-runtime vibium {' '.join(args)} unexpectedly succeeded")
    return result


api = json.loads(run("api").stdout)
if api["api"] != "carbon-vibium/v1" or "generateTests" not in api["carbonExtensions"]:
    raise AssertionError("CARBON Vibium API surface is incomplete")

with tempfile.TemporaryDirectory(prefix="carbon-vibium-") as temporary:
    root = Path(temporary)
    fake = root / "vibium"
    fake.write_text(
        """#!/usr/bin/env python3
import json, pathlib, sys
if '--version' in sys.argv:
    print('vibium v99.1.2-test')
    raise SystemExit(0)
args = [arg for arg in sys.argv[1:] if arg not in {'--json', '--headless'}]
if args[:2] == ['dialog', 'accept']:
    state = pathlib.Path(__file__).with_suffix('.dialog-count')
    count = int(state.read_text() or '0') if state.exists() else 0
    state.write_text(str(count + 1))
    if count < 2:
        print(json.dumps({'ok': False, 'error': 'no such alert'}))
        raise SystemExit(1)
print(json.dumps({'ok': True, 'result': ' '.join(args)}))
""",
        encoding="utf-8",
    )
    fake.chmod(0o755)

    doctor = json.loads(run("doctor", "--root", str(root), "--binary", str(fake)).stdout)
    if not doctor["available"] or "99.1.2-test" not in doctor["version"]:
        raise AssertionError("installed Vibium detection failed")

    manifest = json.loads(run("manifest").stdout)
    if "vibium.command" not in manifest["operations"] or manifest["transport"] != "cli":
        raise AssertionError("executable Vibium adapter manifest is incomplete")

    executed = json.loads(run(
        "exec", "--root", str(root), "--binary", str(fake), "--headless", "--",
        "go", "https://example.test",
    ).stdout)
    if not executed["ok"] or executed["nativeResult"]["result"] != "go https://example.test":
        raise AssertionError("native Vibium CLI compatibility did not preserve the command")
    session_dir = Path(executed["carbonSession"]["sessionDir"])
    if executed["carbonSession"]["operations"] != 1 or not (session_dir / "operations.jsonl").is_file():
        raise AssertionError("native Vibium execution was not recorded in CARBON")

    dialog = json.loads(run(
        "exec", "--root", str(root), "--binary", str(fake),
        "--dialog-wait-ms", "1000", "--", "dialog", "accept",
    ).stdout)
    if not dialog["ok"] or dialog["dialogWait"]["attempts"] != 3 or not dialog["dialogWait"]["waited"]:
        raise AssertionError("asynchronous dialog acceptance was not retried within the bounded wait")

    secret = "plain-test-password-value"
    filled = json.loads(run(
        "exec", "--root", str(root), "--binary", str(fake), "--",
        "fill", "@e2", secret,
    ).stdout)
    if secret in json.dumps(filled) or filled["command"][-1] != "[REDACTED]":
        raise AssertionError("native input value was returned by the CARBON compatibility API")
    fill_artifacts = Path(filled["artifactDir"])
    durable_fill = (fill_artifacts / "command.json").read_text(encoding="utf-8")
    durable_fill += (fill_artifacts / "stdout.txt").read_text(encoding="utf-8")
    if secret in durable_fill:
        raise AssertionError("native input value was retained in CARBON artifacts")

    test_file = root / "existing_vibium_test.py"
    test_file.write_text("print('existing Vibium test passed')\n", encoding="utf-8")
    test_run = json.loads(run(
        "run-test", "--root", str(root), "--file", test_file.name,
    ).stdout)
    if not test_run["ok"] or test_run["carbonSession"]["operations"] != 1:
        raise AssertionError("existing Vibium test execution was not recorded")

    escaped = run(
        "run-test", "--root", str(root), "--file", str(PLUGIN / "README.md"), ok=False
    )
    if "inside the selected project root" not in escaped.stderr:
        raise AssertionError("project-root containment did not fail closed")

    blocked = run(
        "exec", "--root", str(root), "--binary", str(fake),
        "--action-class", "paid", "--", "click", "@e1", ok=False,
    )
    if "requires --approve-consequential" not in blocked.stderr:
        raise AssertionError("consequential Vibium actions did not require scoped approval")

print("PASS: native Vibium CLI compatibility, bounded asynchronous-dialog synchronization, existing-test execution, CARBON ledgers, generation API discovery, containment, and authority gates verified.")
