"""
Web Application Pentester Agent
"""

import os
from dotenv import load_dotenv
from openai import AsyncOpenAI

from cai.sdk.agents import Agent, OpenAIChatCompletionsModel
from cai.util import load_prompt_template, create_system_prompt_renderer
from cai.agents.guardrails import get_security_guardrails

# Core tools
from cai.tools.reconnaissance.generic_linux_command import generic_linux_command
from cai.tools.reconnaissance.exec_code import execute_code
from cai.tools.web.headers import web_request_framework
from cai.tools.web.js_surface_mapper import js_surface_mapper

# Optional OSINT search (requires PERPLEXITY_API_KEY)
from cai.tools.web.search_web import make_web_search_with_explanation

load_dotenv()
model_name = os.getenv("CAI_MODEL", "alias1")

# Load prompt (expects placement under src/cai/prompts/)
web_pentester_system_prompt = load_prompt_template("prompts/system_web_pentester.md")

# Assemble tools with minimal, high-signal set
tools = [
    generic_linux_command,   # shell one-liners (httpie/curl/waybackurls/etc if installed)
    execute_code,            # light parsing/diffing/payload crafting
    web_request_framework,   # HTTP request + response/header security analysis
    js_surface_mapper,       # JS asset surface extraction (endpoints/ops/ws)
]

# Conditional: add web search helper when available
if os.getenv("PERPLEXITY_API_KEY"):
    tools.append(make_web_search_with_explanation)

# Security guardrails to dampen prompt-injection from untrusted web content
input_guardrails, output_guardrails = get_security_guardrails()

# Instantiate agent
web_pentester_agent = Agent(
    name="Web App Pentester",
    description=(
        "Agent specializing in web application penetration testing."
    ),
    instructions=create_system_prompt_renderer(web_pentester_system_prompt),
    tools=tools,
    input_guardrails=input_guardrails,
    output_guardrails=output_guardrails,
    model=OpenAIChatCompletionsModel(
        model=model_name,
        openai_client=AsyncOpenAI(),
    ),
)

def transfer_to_web_pentester(**kwargs):  # pylint: disable=unused-argument
    """
    Optional handoff helper for swarm patterns.
    Accepts arbitrary kwargs for compatibility; returns the agent instance.
    """
    return web_pentester_agent
