"""
Sample AI Agent — generated by AIR Blackbox demo.

This agent demonstrates common patterns that the compliance scanner checks.
Some are good practices (logging, error handling). Others are gaps
(no user identity binding, no action boundaries).

Run: air-blackbox comply -v  to see the full compliance report.
"""
import logging
from dataclasses import dataclass
from typing import Optional
from openai import OpenAI

logger = logging.getLogger(__name__)


@dataclass
class AgentConfig:
    """Configuration for the sample agent."""
    model: str = "gpt-4o-mini"
    max_tokens: int = 1000
    max_retries: int = 3


def run_agent(query: str, config: Optional[AgentConfig] = None) -> str:
    """Run the AI agent with a user query.

    Args:
        query: The user's input query
        config: Optional agent configuration

    Returns:
        The agent's response text
    """
    config = config or AgentConfig()
    client = OpenAI()

    # ✅ GOOD: Error handling around LLM calls
    try:
        logger.info(f"Agent processing query: {query[:50]}...")
        response = client.chat.completions.create(
            model=config.model,
            max_tokens=config.max_tokens,
            messages=[{"role": "user", "content": query}],
        )
        result = response.choices[0].message.content
        logger.info(f"Agent completed. Tokens: {response.usage.total_tokens}")
        return result

    except Exception as e:
        # ✅ GOOD: Fallback on error
        logger.error(f"Agent failed: {e}")
        return f"Sorry, I encountered an error: {e}"


def send_email(to: str, subject: str, body: str) -> bool:
    """Send an email on behalf of the user.

    ⚠️ GAP: No user_id tracking — who authorized this?
    ⚠️ GAP: No action audit trail — was this logged?
    ⚠️ GAP: No action boundaries — can the agent send to anyone?
    """
    # This action is NOT logged, NOT tied to a user, NOT bounded
    print(f"Sending email to {to}: {subject}")
    return True


def search_web(query: str) -> str:
    """Search the web for information."""
    logger.info(f"Web search: {query}")
    return f"Results for: {query}"


if __name__ == "__main__":
    result = run_agent("What is the EU AI Act?")
    print(result)
