import google.generativeai as genai
import os
import json
from typing import Dict, List, Optional

class LegalAIEngine:
    def __init__(self, api_key: str = None):
        """Initialize the Legal AI Engine with Google Gemini"""
        if api_key:
            genai.configure(api_key=api_key)
        else:
            # In production, this should come from environment variables
            genai.configure(api_key=os.getenv('GEMINI_API_KEY', 'demo-key'))
        
        # Initialize the model
        self.model = genai.GenerativeModel('gemini-pro')
        
        # Legal context for Saudi Arabia and Jordan
        self.legal_contexts = {
            'SA': {
                'name': 'Saudi Arabia',
                'legal_system': 'Civil law system based on Islamic Sharia law',
                'key_principles': [
                    'Contracts must comply with Islamic Sharia principles',
                    'Interest (Riba) is prohibited in financial contracts',
                    'Contracts must be clear and unambiguous',
                    'Good faith and fair dealing are required'
                ],
                'common_contract_types': [
                    'Employment contracts', 'Commercial agreements', 
                    'Real estate contracts', 'Partnership agreements',
                    'Service agreements', 'Supply contracts'
                ]
            },
            'JO': {
                'name': 'Jordan',
                'legal_system': 'Civil law system with Islamic law influences',
                'key_principles': [
                    'Contracts must be in accordance with public order and morals',
                    'Freedom of contract within legal boundaries',
                    'Good faith in contract performance',
                    'Protection of weaker contracting parties'
                ],
                'common_contract_types': [
                    'Employment contracts', 'Commercial agreements',
                    'Real estate contracts', 'Construction contracts',
                    'Technology agreements', 'Distribution agreements'
                ]
            }
        }

    def generate_contract(self, contract_type: str, jurisdiction: str, 
                         requirements: Dict, user_input: str = "", parties: List[Dict] = None) -> str:
        """Generate a contract based on type, jurisdiction, and requirements"""
        
        legal_context = self.legal_contexts.get(jurisdiction, {})
        parties_info = ""
        if parties:
            parties_info = "\nParties Involved:\n"
            for i, party in enumerate(parties):
                parties_info += f"Party {i+1}:\n"
                for key, value in party.items():
                    parties_info += f"  {key.replace('_', ' ').title()}: {value}\n"

        prompt = f"""
        You are a legal AI assistant specializing in {legal_context.get("name", "general")} law.
        
        Legal System Context: {legal_context.get("legal_system", "General legal principles")}
        
        Key Legal Principles:
        {chr(10).join("- " + principle for principle in legal_context.get("key_principles", []))}
        
        Task: Generate a comprehensive {contract_type} contract for {legal_context.get("name", "general jurisdiction")}.
        
        Requirements:
        {json.dumps(requirements, indent=2)}
        
        Additional User Input: {user_input}
        {parties_info}
        
        Please generate a complete, legally sound contract that:
        1. Follows the legal principles of {legal_context.get("name", "the jurisdiction")}
        2. Includes all necessary clauses for a {contract_type}
        3. Uses appropriate legal terminology
        4. Includes standard protective clauses
        5. Is clear and unambiguous
        
        Format the contract with proper headings, sections, and legal structure.
        """      
        try:
            response = self.model.generate_content(prompt)
            return response.text
        except Exception as e:
            import traceback
            traceback.print_exc()
            return f"Error generating contract: {str(e)}"

    def draft_clause(self, clause_type: str, jurisdiction: str, 
                    context: str = "", specific_requirements: str = "") -> str:
        """Draft a specific contract clause"""
        
        legal_context = self.legal_contexts.get(jurisdiction, {})
        
        prompt = f"""
        You are a legal AI assistant specializing in {legal_context.get('name', 'general')} law.
        
        Task: Draft a {clause_type} clause for a contract under {legal_context.get('name', 'general')} jurisdiction.
        
        Legal Context: {legal_context.get('legal_system', 'General legal principles')}
        
        Contract Context: {context}
        
        Specific Requirements: {specific_requirements}
        
        Please draft a comprehensive {clause_type} clause that:
        1. Complies with {legal_context.get('name', 'applicable')} law
        2. Is legally enforceable
        3. Protects the interests of the contracting parties
        4. Uses appropriate legal language
        5. Includes necessary sub-clauses and conditions
        
        Provide only the clause text with proper legal formatting.
        """
        
        try:
            response = self.model.generate_content(prompt)
            return response.text
        except Exception as e:
            return f"Error drafting clause: {str(e)}"

    def review_contract(self, contract_content: str, jurisdiction: str, 
                       review_type: str = "general") -> Dict:
        """Review a contract and provide analysis"""
        
        legal_context = self.legal_contexts.get(jurisdiction, {})
        
        prompt = f"""
        You are a legal AI assistant specializing in {legal_context.get('name', 'general')} law.
        
        Task: Conduct a {review_type} review of the following contract under {legal_context.get('name', 'general')} jurisdiction.
        
        Legal System: {legal_context.get('legal_system', 'General legal principles')}
        
        Key Legal Principles to Check:
        {chr(10).join('- ' + principle for principle in legal_context.get('key_principles', []))}
        
        Contract to Review:
        {contract_content}
        
        Please provide a comprehensive review including:
        1. Compliance issues with {legal_context.get('name', 'applicable')} law
        2. Potential legal risks and red flags
        3. Missing clauses or provisions
        4. Ambiguous or unclear language
        5. Recommendations for improvement
        6. Overall risk assessment (Low/Medium/High)
        
        Format your response as a JSON object with the following structure:
        {{
            "compliance_issues": ["list of compliance issues"],
            "legal_risks": ["list of potential risks"],
            "missing_clauses": ["list of missing important clauses"],
            "ambiguous_language": ["list of unclear provisions"],
            "recommendations": ["list of improvement recommendations"],
            "risk_level": "Low/Medium/High",
            "summary": "Overall assessment summary"
        }}
        """
        
        try:
            response = self.model.generate_content(prompt)
            # Try to parse as JSON, fallback to text if parsing fails
            try:
                return json.loads(response.text)
            except json.JSONDecodeError:
                return {
                    "error": "Failed to parse review results",
                    "raw_response": response.text,
                    "risk_level": "Unknown"
                }
        except Exception as e:
            return {
                "error": f"Error reviewing contract: {str(e)}",
                "risk_level": "Unknown"
            }

    def get_legal_advice(self, question: str, jurisdiction: str) -> str:
        """Provide legal advice for a specific question"""
        
        legal_context = self.legal_contexts.get(jurisdiction, {})
        
        prompt = f"""
        You are a legal AI assistant specializing in {legal_context.get('name', 'general')} law.
        
        Legal System: {legal_context.get('legal_system', 'General legal principles')}
        
        Question: {question}
        
        Please provide legal advice considering:
        1. The legal framework of {legal_context.get('name', 'the jurisdiction')}
        2. Relevant legal principles and precedents
        3. Practical implications
        4. Potential risks and considerations
        
        Note: This advice is for informational purposes only and should not replace consultation with a qualified legal professional.
        """
        
        try:
            response = self.model.generate_content(prompt)
            return response.text
        except Exception as e:
            return f"Error providing legal advice: {str(e)}"

    def suggest_clauses(self, contract_type: str, jurisdiction: str) -> List[str]:
        """Suggest important clauses for a specific contract type"""
        
        legal_context = self.legal_contexts.get(jurisdiction, {})
        
        prompt = f"""
        You are a legal AI assistant specializing in {legal_context.get('name', 'general')} law.
        
        Task: Suggest essential clauses for a {contract_type} contract under {legal_context.get('name', 'general')} jurisdiction.
        
        Legal System: {legal_context.get('legal_system', 'General legal principles')}
        
        Please provide a list of essential clauses that should be included in a {contract_type} contract, considering:
        1. Legal requirements in {legal_context.get('name', 'the jurisdiction')}
        2. Industry best practices
        3. Risk mitigation
        4. Enforceability
        
        Format your response as a simple list of clause names, one per line.
        """
        
        try:
            response = self.model.generate_content(prompt)
            # Split response into lines and clean up
            clauses = [clause.strip() for clause in response.text.split('\n') if clause.strip()]
            return clauses
        except Exception as e:
            return [f"Error suggesting clauses: {str(e)}"]

