#!/usr/bin/env python3
"""Verify CARBON's global local-execution profile and secret boundary."""

from __future__ import annotations

import json
import os
import subprocess
import tempfile
from pathlib import Path


PLUGIN = Path(__file__).resolve().parents[1]
RUNTIME = PLUGIN / "bin" / "carbon-runtime"
PASSWORD = "Contract-Only-Password-42!"
AI_KEY = "Contract-Only-AI-Key-987654321"


def run(environment: dict[str, str], *arguments: str) -> subprocess.CompletedProcess[str]:
    result = subprocess.run([str(RUNTIME), *arguments], env=environment, text=True, capture_output=True)
    if result.returncode:
        raise AssertionError(result.stderr or result.stdout)
    return result


with tempfile.TemporaryDirectory(prefix="carbon-global-context-") as temporary:
    home = Path(temporary) / "home"
    project = Path(temporary) / "project"
    config_dir = home / ".config" / "carbon"
    documents = config_dir / "context-documents"
    project.mkdir(parents=True)
    documents.mkdir(parents=True)
    context_document = documents / "context.md"
    context_document.write_text("Use the QA tenant and synthetic records only.\n", encoding="utf-8")
    context_document.chmod(0o600)
    symlink = documents / "outside-link.md"
    outside = Path(temporary) / "outside.md"
    outside.write_text("Do not load through the symlink.\n", encoding="utf-8")
    symlink.symlink_to(outside)
    (config_dir / "execution-password").write_text(PASSWORD, encoding="utf-8")
    (config_dir / "execution-password").chmod(0o600)
    (config_dir / "ai-api-key").write_text(AI_KEY, encoding="utf-8")
    (config_dir / "ai-api-key").chmod(0o600)
    (config_dir / "config.json").write_text(json.dumps({
        "executionUsername": "global-qa@example.com",
        "customExecutionPrompt": "Apply the configured QA tenant and preserve cleanup evidence.",
        "aiProvider": "openai",
        "aiModel": "contract-vision-model",
        "contextDocuments": [
            {"id": "valid", "name": "context.md", "path": str(context_document)},
            {"id": "link", "name": "outside-link.md", "path": str(symlink)},
        ],
    }), encoding="utf-8")
    (config_dir / "config.json").chmod(0o600)

    environment = dict(os.environ)
    environment.update({"HOME": str(home), "CARBON_CREDENTIAL_STORE": "file"})
    environment.pop("CARBON_TEST_USERNAME", None)
    environment.pop("CARBON_TEST_PASSWORD", None)
    environment.pop("CARBON_GLOBAL_PROMPT", None)
    environment.pop("OPENAI_API_KEY", None)
    environment.pop("CARBON_AI_API_KEY", None)

    safe = json.loads(run(environment, "context", "show").stdout)
    assert safe["schema"] == "carbon.execution-context/v1"
    assert safe["username"] == "global-qa@example.com"
    assert safe["passwordConfigured"] is True and safe["passwordValueReturned"] is False
    resolved_context_document = str(context_document.resolve())
    assert len(safe["contextDocuments"]) == 1 and safe["contextDocuments"][0]["path"] == resolved_context_document
    assert PASSWORD not in json.dumps(safe)
    assert safe["aiReview"]["configured"] is True and safe["aiReview"]["provider"] == "openai"
    assert safe["aiReview"]["model"] == "contract-vision-model" and safe["aiReview"]["keyValueReturned"] is False
    assert AI_KEY not in json.dumps(safe)

    checker = (
        "import json,os,sys;"
        "docs=json.loads(os.environ.get('CARBON_CONTEXT_DOCUMENTS','[]'));"
        "ok=(os.environ.get('CARBON_TEST_USERNAME')=='global-qa@example.com' and "
        f"os.environ.get('CARBON_TEST_PASSWORD')=={PASSWORD!r} and "
        "'configured QA tenant' in os.environ.get('CARBON_GLOBAL_PROMPT','') and "
        f"docs==[{resolved_context_document!r}]);"
        "print('runner context PASS' if ok else 'runner context FAIL');sys.exit(0 if ok else 3)"
    )
    executed = run(environment, "context", "exec", "--", "python3", "-c", checker)
    assert executed.stdout.strip() == "runner context PASS" and PASSWORD not in executed.stdout
    redacted = run(environment, "context", "exec", "--", "python3", "-c", "import os;print(os.environ['CARBON_TEST_PASSWORD'])")
    assert redacted.stdout.strip() == "[REDACTED_CARBON_TEST_PASSWORD]" and PASSWORD not in redacted.stdout
    ai_redacted = run(environment, "context", "exec", "--", "python3", "-c", "import os;print(os.environ['OPENAI_API_KEY'])")
    assert ai_redacted.stdout.strip() == "[REDACTED_CARBON_AI_API_KEY]" and AI_KEY not in ai_redacted.stdout

    (project / "app.py").write_text("def health(): return 'ok'\n", encoding="utf-8")
    run(environment, "framework", "prepare", "--root", str(project), "--request", "test this", "--target", "local")
    plan = json.loads((project / ".carbon" / "framework" / "orchestration-plan.json").read_text(encoding="utf-8"))
    global_context = plan["globalExecutionContext"]
    assert global_context["configured"] is True
    assert global_context["customPrompt"].startswith("Apply the configured")
    assert global_context["contextDocuments"][0]["path"] == resolved_context_document
    assert plan["credentialSources"] == ["CARBON global execution credential profile"]
    assert PASSWORD not in json.dumps(plan)

print("PASS: global test/model credentials, prompt, context documents, child-runner injection, framework application, and secret non-disclosure verified")
