from typing import Optional
import json
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from armorer.profiles import RiskProfile, NetworkPolicy, FilesystemPolicy
from armorer.agent import BaseAgent
from armorer.scanner import ScanResult

console = Console()

def assess_risk(app_name: str, scan_result: Optional[ScanResult] = None) -> RiskProfile:
    console.print(Panel.fit(f"🛡️  Armorer Security Interview: {app_name}", style="bold green"))
    console.print("I am your AI Security Architect. I need to ask you a few questions to design the right security profile for your needs.\n")

    agent = BaseAgent() # Uses default provider
    
    # Context from Scan
    scan_context = ""
    if scan_result:
        scan_context = f"\n    [IMPORTANT] Vulnerability Scan Results:\n    - Score: {scan_result.score}\n"
        if scan_result.issues:
            scan_context += "    - Issues Found:\n"
            for issue in scan_result.issues:
                scan_context += f"      * {issue}\n"
        
        if scan_result.critical_found:
            scan_context += "\n    CRITICAL VULNERABILITIES DETECTED. YOU MUST RECOMMEND 'SANDBOXED' UNLESS THERE IS AN EXTREME JUSTIFICATION."

    # Initial System Prompt
    system_prompt = f"""
    You are a Security Architect Agent. Your goal is to interview the user to determine the "Risk Profile" for installing an agentic application.
    {scan_context}
    
    The Profiles are:
    1. SANDBOXED: For casual chat/brainstorming. No file access.
    2. SCOPED_READ: Read-only access to specific folders.
    3. SCOPED_WRITE: Read/Write access to specific folders.
    4. HIGH_RISK: Broad system access (discouraged).

    Ask probing questions to understand:
    - What is the primary use case?
    - Does it need file access? If so, read or write?
    - Does it need internet access?

    After 2-3 questions, when you are confident, output the classification in this EXACT JSON format (no markdown):
    {{
        "profile": "PROFILE_NAME", 
        "reasoning": "Brief explanation",
        "network_needed": true/false
    }}
    
    If you are not yet confident, just output the next question as plain text.
    """

    import uuid
    session_id = f"armorer-interview-{uuid.uuid4()}"
    
    agent.init_agent(
        system_prompt=system_prompt,
        session_id=session_id,
        agent_name="armorer:interview"
    )
    
    # Start the conversation
    next_response = agent.run(user_input="Start the interview.")
    
    while True:
        # Check if the response is the final JSON decision
        try:
            # Attempt to find JSON blob if embedded
            import re
            json_match = re.search(r'\{.*\}', next_response, re.DOTALL)
            if json_match:
                decision_json = json_match.group(0)
                decision = json.loads(decision_json)
                
                # Check for profile key to confirm it's the decision JSON
                if "profile" in decision:
                    # Map to Python Objects
                    profile_name = decision.get("profile", "SANDBOXED")
                    network = NetworkPolicy.OPEN if decision.get("network_needed") else NetworkPolicy.WHITELIST
                    
                    fs_policy = FilesystemPolicy.NONE
                    if profile_name == "SCOPED_READ": fs_policy = FilesystemPolicy.SCOPED
                    elif profile_name == "SCOPED_WRITE": fs_policy = FilesystemPolicy.SCOPED
                    elif profile_name == "HIGH_RISK": fs_policy = FilesystemPolicy.HOME
                    
                    console.print(f"\n[bold blue]Assessment Complete:[/bold blue] {decision.get('reasoning')}")
                    
                    return RiskProfile(
                        name=profile_name,
                        description=decision.get("reasoning", "AI Determined"),
                        network_policy=network,
                        filesystem_policy=fs_policy
                    )
        except Exception:
            pass # Not JSON, continue conversation

        # Print Agent Question
        console.print(f"[bold cyan]Armorer:[/bold cyan] {next_response}")
        
        # Get User Answer
        user_input = Prompt.ask("[bold]You[/bold]")
        
        # Run Next Turn
        next_response = agent.run(user_input=user_input)

