try:
    from google.adk.agents.context_cache_config import ContextCacheConfig
except (ImportError, AttributeError, ModuleNotFoundError):
    ContextCacheConfig = None

import ast
import logging
import os

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from agent_ops_cockpit.ops.auditors.rag_fidelity import RAGFidelityAuditor
from agent_ops_cockpit.ops.discovery import DiscoveryEngine

console = Console()
app = typer.Typer(help="RAG Truth-Sayer SME: Audits RAG pipelines for grounding and fidelity.")

def perform_audit(path: str):
    """Internal helper to run the audit logic."""
    console.print(Panel.fit('🧗 [bold blue]RAG TRUTH-SAYER: FIDELITY AUDIT[/bold blue]', border_style='blue'))
    
    auditor = RAGFidelityAuditor()
    discovery = DiscoveryEngine(path)
    all_findings = []
    
    for file_path in discovery.walk(path):
        if not file_path.endswith('.py'):
            continue
            
        # Skip library files and specific internal files
        if discovery.is_library_file(file_path) or 'auditors' in file_path or 'frameworks.py' in file_path:
            continue

        try:
            with open(file_path, 'r', errors='ignore') as f:
                content = f.read()
            tree = ast.parse(content)
            findings = auditor.audit(tree, content, file_path)
            all_findings.extend(findings)
        except Exception as e:
            logging.debug(f"Error processing file {file_path}: {e}")
            pass
    
    if not all_findings:
        console.print("✅ [green]No RAG-specific risks detected or no RAG pattern found.[/green]")
        return
    
    table = Table(title="RAG Fidelity Findings", show_header=True, header_style="bold magenta")
    table.add_column("Issue", style="cyan")
    table.add_column("Location", style="dim")
    table.add_column("ROI", style="green")

    for f in all_findings:
        table.add_row(f.title, f"{os.path.basename(f.file_path)}:{f.line_number or ''}", f.roi)
        # Orchestrator capture line
        console.print(f"ACTION: {f.file_path}:{f.line_number or 1} | {f.title} | {f.description}")
    
    console.print(table)

@app.callback(invoke_without_command=True)
def main(
    ctx: typer.Context, 
    path: str = typer.Option('.', '--path', '-p', help='Path to the agent project to audit')
):
    """
    Standardized CLI Hub. Runs audit if no subcommand is provided.
    """
    if ctx.invoked_subcommand is None:
        perform_audit(path)

@app.command(name="audit")
def audit_command(path: str = typer.Option('.', '--path', '-p', help='Path to the agent project to audit')):
    """Run the RAG Fidelity Audit (Standard Subcommand)."""
    perform_audit(path)

@app.command(name="blueprint")
def generate_mcp_blueprint(path: str = typer.Option('.', '--path', '-p')):
    """[v1.8.1] Auto-Generate MCP Wrappers from legacy tool code."""
    console.print("🔧 [bold blue]Generating MCP Modernization Blueprint...[/bold blue]")
    
    discovery = DiscoveryEngine(path)
    brain = discovery.find_agent_brain()
    
    mcp_code = f"""# 🛰️ Model Context Protocol (MCP) Server Wrapper
# Generated by AgentOps Cockpit v1.8.1
# Modernizes legacy logic from: {os.path.basename(brain)}

import mcp.server
from mcp.types import Tool
import asyncio

app = mcp.server.Server("modernized-mcp-server")

@app.list_tools()
async def list_tools() -> list[Tool]:
    # TODO: Define your modernized tooling schema here
    return [
        Tool(
            name="mcp_tool",
            description="Modernized entry point.",
            inputSchema={{
                "type": "object",
                "properties": {{
                    "query": {{"type": "string"}}
                }},
                "required": ["query"]
            }}
        )
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list:
    if name == "mcp_tool":
        # PIVOT POINT: Port your tool logic here
        return [{{ "type": "text", "text": "Logic executed via MCP Protocol." }}]
    raise ValueError(f"Unknown tool: {{name}}")

async def main():
    async with mcp.server.stdio.stdio_server() as (read, write):
        await app.run(read, write, app.create_initialization_options())

if __name__ == "__main__":
    asyncio.run(main())
"""
    output_path = os.path.join(path, "mcp_server.py")
    with open(output_path, "w") as f:
        f.write(mcp_code)
    
    console.print(f"✨ [bold green]MCP Wrapper generated:[/bold green] {output_path}")
    console.print("[dim]Next step: Run 'pip install mcp' and migrate your logic into call_tool().[/dim]")

if __name__ == "__main__":
    app()
