from __future__ import annotations

import os
import json
import subprocess


CLAUDE_WEBSEARCH_LINE = (
    "You have access to WebSearch. Use it to verify claims and find source URLs."
)


def call_opus(prompt: str) -> str:
    """Call claude --print with CLAUDECODE unset to allow nesting."""
    env = {key: value for key, value in os.environ.items() if key != "CLAUDECODE"}
    claude_bin = env.get("AI_LANDSCAPE_REVIEW_CLAUDE_BIN", "claude")
    result = subprocess.run(
        [claude_bin, "--print", "--output-format", "json", "-p", prompt],
        capture_output=True,
        text=True,
        env=env,
        timeout=300,
        check=False,
    )
    if result.returncode != 0:
        raise RuntimeError(f"claude --print failed: {result.stderr.strip()}")
    try:
        payload = json.loads(result.stdout)
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"claude --print returned invalid JSON: {result.stdout[:200]!r}") from exc

    output = payload.get("result", "").strip()
    if not output:
        raise RuntimeError("claude --print returned empty output")
    return output
