#!/usr/bin/env python3
"""Start an inspected provider-side Claude Code project; never export an agent."""
import argparse
import json
import os
from pathlib import Path
import sys


KEYS = {"claude_binary", "workspace", "mcp_config", "model",
        "reviewed_for_shared_synthetic_data"}


def absolute_path(value, *, directory=False, executable=False):
    if not isinstance(value, str) or not value or not Path(value).is_absolute():
        raise ValueError("configuration paths must be explicit absolute paths")
    path = Path(value).resolve(strict=True)
    if not (path.is_dir() if directory else path.is_file()):
        raise ValueError("configured path has the wrong file type")
    if executable and not os.access(path, os.X_OK):
        raise ValueError("Claude binary is not executable")
    return path


def launch_spec(config_path):
    config = json.loads(Path(config_path).read_text(encoding="utf-8"))
    if not isinstance(config, dict) or set(config) != KEYS:
        raise ValueError("configuration must contain exactly the example's five fields")
    if config["reviewed_for_shared_synthetic_data"] is not True:
        raise ValueError("provider review of shared synthetic data is required")
    binary = absolute_path(config["claude_binary"], executable=True)
    workspace = absolute_path(config["workspace"], directory=True)
    mcp = absolute_path(config["mcp_config"])
    if not (workspace / "CLAUDE.md").is_file():
        raise ValueError("the existing project must have an inspected CLAUDE.md")
    mcp_data = json.loads(mcp.read_text(encoding="utf-8"))
    if not isinstance(mcp_data, dict) or not isinstance(mcp_data.get("mcpServers"), dict):
        raise ValueError("MCP configuration must contain an mcpServers object")
    model = config["model"]
    if not isinstance(model, str) or not model.strip() or model.startswith("-"):
        raise ValueError("provider must select an available model explicitly")
    argv = [str(binary), "-p", "--output-format", "text",
            "--permission-mode", "dontAsk", "--tools", "Read,Glob,Grep",
            "--mcp-config", str(mcp), "--strict-mcp-config",
            "--no-session-persistence", "--max-turns", "8", "--model", model]
    return workspace, argv


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", required=True, help="Provider-owned JSON configuration")
    parser.add_argument("--check", action="store_true", help="Validate files only; no Claude execution")
    args = parser.parse_args()
    try:
        workspace, argv = launch_spec(args.config)
        if args.check:
            print("Configuration paths and shape checked; model, tools and authorization not tested.")
            return 0
        os.chdir(workspace)
        # No shell, eval, dotenv import, prompt rewriting, resume or credential copying.
        # exec preserves stdin/stdout/stderr, child exit status and Runtime signal delivery.
        os.execv(argv[0], argv)
    except (OSError, ValueError) as error:
        # Do not print config values: MCP files may contain sensitive settings.
        print(f"teammate-agent: cannot start ({type(error).__name__}); check paths, JSON and review flag", file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main())
