"""Test structured output with each CLI."""

import asyncio
from pathlib import Path

from deliberate.adapters.cli_adapter import CLIAdapter


async def test_claude():
    """Test Claude with execution schema."""
    print("=" * 60)
    print("Testing Claude CLI with structured output")
    print("=" * 60)

    adapter = CLIAdapter(
        name="claude",
        command=["claude", "--dangerously-skip-permissions", "-p"],
        model_id="claude-sonnet-4-5-20250929",
    )

    task = """Review the file at src/deliberate/cli.py and suggest 2-3 improvements to the help text.

Respond in the JSON format specified with:
- summary: brief overview of your suggestions
- changes: list of specific help text improvements
- reasoning: why these changes would help users
"""

    try:
        result = await adapter.run_agentic(
            task=task,
            working_dir=str(Path.cwd()),
            schema_name="execution",
            timeout_seconds=60,
        )

        print(f"\nSuccess!")
        print(f"Tokens: {result.token_usage}")
        print(f"Duration: {result.duration_seconds:.2f}s")
        print(f"Content length: {len(result.content)} chars")
        print(f"\nContent preview:")
        print(result.content[:500])

        if result.raw_response:
            print(f"\nRaw response keys: {list(result.raw_response.keys())}")

        # Try to estimate cost
        cost = adapter.estimate_cost(result.token_usage)
        print(f"\nEstimated cost: ${cost:.4f}")

    except Exception as e:
        print(f"\nFailed: {e}")


async def test_gemini():
    """Test Gemini with execution schema."""
    print("\n" + "=" * 60)
    print("Testing Gemini CLI with structured output")
    print("=" * 60)

    adapter = CLIAdapter(
        name="gemini",
        command=["gemini", "--yolo"],  # Use --yolo, task piped via stdin
        model_id="gemini-2.0-flash-exp",
        # GEMINI_API_KEY should be set in environment
    )

    task = """List 3 potential improvements to the help text in src/deliberate/cli.py.

Respond with:
- summary: brief overview
- changes: list of improvements (each with file and description)
- reasoning: why these help
"""

    try:
        result = await adapter.run_agentic(
            task=task,
            working_dir=str(Path.cwd()),
            schema_name=None,  # Gemini doesn't support JSON schema validation
            timeout_seconds=60,
        )

        print(f"\nSuccess!")
        print(f"Tokens: {result.token_usage}")
        print(f"Duration: {result.duration_seconds:.2f}s")
        print(f"Content preview:")
        print(result.content[:500])

        cost = adapter.estimate_cost(result.token_usage)
        print(f"\nEstimated cost: ${cost:.4f}")

    except Exception as e:
        print(f"\nFailed: {e}")


async def test_codex():
    """Test Codex with execution schema."""
    print("\n" + "=" * 60)
    print("Testing Codex CLI with structured output")
    print("=" * 60)

    adapter = CLIAdapter(
        name="codex",
        command=["codex", "-s", "danger-full-access", "-a", "never", "exec"],
        model_id="o1",
    )

    task = """Suggest 2 improvements to help text in src/deliberate/cli.py. Be brief."""

    try:
        result = await adapter.run_agentic(
            task=task,
            working_dir=str(Path.cwd()),
            schema_name=None,  # Test without schema first
            timeout_seconds=60,
        )

        print(f"\nSuccess!")
        print(f"Tokens: {result.token_usage}")
        print(f"Duration: {result.duration_seconds:.2f}s")
        print(f"Content preview:")
        print(result.content[:500])

        cost = adapter.estimate_cost(result.token_usage)
        print(f"\nEstimated cost: ${cost:.4f}")

    except Exception as e:
        print(f"\nFailed: {e}")


async def main():
    """Run all tests."""
    await test_claude()
    await test_gemini()
    await test_codex()


if __name__ == "__main__":
    asyncio.run(main())
