"""
Brynq MCP Skill: Secure Code Review (Multi-Model Debate)
"""
from brynq.llm_router import chat
import json
import re

class SecureCodeReviewer:
    def __init__(self, max_cycles=3):
        self.primary_backend = "claude"
        self.primary_model = "auto"
        self.challenger_backend = "gemini"
        self.challenger_model = "auto"
        self.max_cycles = max_cycles

    def scan_vulnerabilities(self, source_code: str) -> dict:
        vulnerabilities = []
        debate_log = []
        
        # Cycle 1: Primary Model Review
        prompt1 = f"Perform a strict security code review on the following code. Identify any vulnerabilities or security risks. Be specific.\n\nCode:\n{source_code}"
        try:
            primary_review = chat(self.primary_backend, self.primary_model, [{"role": "user", "content": prompt1}])
        except Exception as e:
            primary_review = f"Error calling primary model: {e}"
        debate_log.append({"model": "primary", "content": primary_review})
        
        # Cycle 2: Challenger Model tries to find what the primary missed
        prompt2 = f"A primary code reviewer found the following issues in the code below. Your job is to act as a challenger and find ANY security vulnerabilities or exploits that the primary reviewer missed. Do not repeat their findings.\n\nPrimary Review:\n{primary_review}\n\nCode:\n{source_code}"
        try:
            challenger_review = chat(self.challenger_backend, self.challenger_model, [{"role": "user", "content": prompt2}])
        except Exception as e:
            challenger_review = f"Error calling challenger model: {e}"
        debate_log.append({"model": "challenger", "content": challenger_review})
        
        # Synthesis: Combine and determine consensus
        prompt3 = f"Synthesize the security vulnerabilities found by the primary and challenger reviewers into a final, deduplicated list. Output ONLY a valid JSON list of strings, where each string is a unique vulnerability. If no vulnerabilities exist, output an empty list [].\n\nPrimary Review:\n{primary_review}\n\nChallenger Review:\n{challenger_review}"
        
        try:
            synthesis_raw = chat(self.primary_backend, self.primary_model, [{"role": "user", "content": prompt3}])
            debate_log.append({"model": "synthesis", "content": synthesis_raw})
            
            # Extract JSON list
            match = re.search(r'\[.*\]', synthesis_raw, re.DOTALL)
            if match:
                vulnerabilities = json.loads(match.group(0))
            else:
                vulnerabilities = [synthesis_raw]
        except Exception as e:
            vulnerabilities = [f"Synthesis failed: {e}"]
            
        return {
            "status": "scanned", 
            "vulnerabilities_found": len(vulnerabilities), 
            "vulnerabilities": vulnerabilities,
            "consensus": True,
            "debate_cycles": 2,
            "debate_log": debate_log
        }
