from flask import Blueprint, jsonify, request
from src.models.contract import Contract, Template, ReviewResult, db
from src.services.legal_ai import LegalAIEngine
import json

contract_bp = Blueprint('contract', __name__)
legal_ai = LegalAIEngine()

@contract_bp.route('/contracts', methods=['GET'])
def get_contracts():
    """Get all contracts for a user"""
    user_id = request.args.get('user_id')

    if user_id:
        contracts = Contract.query.filter_by(user_id=user_id).all()
    else:
        contracts = Contract.query.all()
    return jsonify([contract.to_dict() for contract in contracts])

@contract_bp.route('/contracts', methods=['POST'])
def create_contract():
    """Create a new contract"""
    data = request.json
    
    contract = Contract(
        title=data['title'],
        content=data.get('content', ''),
        contract_type=data['contractType'],
        jurisdiction=data['jurisdiction'],
        #user_id=data['user_id']
	user_id=data.get("user_id", 1) # Default to 1 if not provided
    )
    
    db.session.add(contract)
    db.session.commit()
    
    return jsonify(contract.to_dict()), 201

@contract_bp.route('/contracts/<int:contract_id>', methods=['GET'])
def get_contract(contract_id):
    """Get a specific contract"""
    contract = Contract.query.get_or_404(contract_id)
    return jsonify(contract.to_dict())

@contract_bp.route('/contracts/<int:contract_id>', methods=['PUT'])
def update_contract(contract_id):
    """Update a contract"""
    contract = Contract.query.get_or_404(contract_id)
    data = request.json
    
    contract.title = data.get('title', contract.title)
    contract.content = data.get('content', contract.content)
    contract.contract_type = data.get('contractType', contract.contract_type)
    contract.jurisdiction = data.get('jurisdiction', contract.jurisdiction)
    contract.status = data.get('status', contract.status)
    
    db.session.commit()
    return jsonify(contract.to_dict())

@contract_bp.route('/contracts/<int:contract_id>', methods=['DELETE'])
def delete_contract(contract_id):
    """Delete a contract"""
    contract = Contract.query.get_or_404(contract_id)
    db.session.delete(contract)
    db.session.commit()
    return '', 204

@contract_bp.route('/contracts/generate', methods=['POST'])
def generate_contract():
    """Generate a new contract using AI"""
    data = request.json

    try:
        contract_content = legal_ai.generate_contract(
            contract_type=data["contractType"],
            jurisdiction=data['jurisdiction'],
            requirements=data.get("requirements", {}),
            user_input=data.get("user_input", ""),
            parties=data.get("parties", [])
        )
        # Create and save the contract
        contract = Contract(
            title=data.get('title', f"{data['contractType']} Contract"),
            content=contract_content,
            contract_type=data['contractType'],
            jurisdiction=data['jurisdiction'],
            #user_id=data['user_id']
            user_id=data.get("user_id", 1) # Default to 1 if not provided
        )

        db.session.add(contract)
        #db.session.commit()
        db.session.commit()
        
        return jsonify(contract.to_dict()), 201
        
    except Exception as e:
        print(e)
        return jsonify({'error': str(e)}), 500

@contract_bp.route('/contracts/<int:contract_id>/review', methods=['POST'])
def review_contract(contract_id):
    """Review a contract using AI"""
    contract = Contract.query.get_or_404(contract_id)
    data = request.json
    
    try:
        review_type = data.get('review_type', 'general')
        review_results = legal_ai.review_contract(
            contract_content=contract.content,
            jurisdiction=contract.jurisdiction,
            review_type=review_type
        )
        
        # Save review results
        review = ReviewResult(
            contract_id=contract_id,
            review_type=review_type,
            findings=json.dumps(review_results),
            risk_level=review_results.get('risk_level', 'Unknown')
        )
        
        db.session.add(review)
        db.session.commit()
        
        return jsonify({
            'review_id': review.id,
            'results': review_results
        }), 201
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@contract_bp.route('/clauses/draft', methods=['POST'])
def draft_clause():
    """Draft a specific clause using AI"""
    data = request.json
    
    try:
        clause_content = legal_ai.draft_clause(
            clause_type=data['clause_type'],
            jurisdiction=data['jurisdiction'],
            context=data.get('context', ''),
            specific_requirements=data.get('specific_requirements', '')
        )
        
        return jsonify({
            'clause_type': data['clause_type'],
            'jurisdiction': data['jurisdiction'],
            'content': clause_content
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@contract_bp.route('/clauses/suggest', methods=['POST'])
def suggest_clauses():
    """Suggest clauses for a contract type"""
    data = request.json
    
    try:
        suggested_clauses = legal_ai.suggest_clauses(
            contract_type=data['contractType'],
            jurisdiction=data['jurisdiction']
        )
        
        return jsonify({
            'contract_type': data['contractType'],
            'jurisdiction': data['jurisdiction'],
            'suggested_clauses': suggested_clauses
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@contract_bp.route('/legal-advice', methods=['POST'])
def get_legal_advice():
    """Get legal advice for a question"""
    data = request.json
    
    try:
        advice = legal_ai.get_legal_advice(
            question=data['question'],
            jurisdiction=data['jurisdiction']
        )
        
        return jsonify({
            'question': data['question'],
            'jurisdiction': data['jurisdiction'],
            'advice': advice
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# Template routes
@contract_bp.route('/templates', methods=['GET'])
def get_templates():
    """Get all templates"""
    jurisdiction = request.args.get('jurisdiction')
    category = request.args.get('category')
    
    query = Template.query
    if jurisdiction:
        query = query.filter_by(jurisdiction=jurisdiction)
    if category:
        query = query.filter_by(category=category)
    
    templates = query.all()
    return jsonify([template.to_dict() for template in templates])

@contract_bp.route('/templates', methods=['POST'])
def create_template():
    """Create a new template"""
    data = request.json
    
    template = Template(
        name=data['name'],
        description=data.get('description', ''),
        content=data['content'],
        category=data['category'],
        jurisdiction=data['jurisdiction']
    )
    
    db.session.add(template)
    db.session.commit()
    
    return jsonify(template.to_dict()), 201

@contract_bp.route('/templates/<int:template_id>', methods=['GET'])
def get_template(template_id):
    """Get a specific template"""
    template = Template.query.get_or_404(template_id)
    return jsonify(template.to_dict())

# Review routes
@contract_bp.route('/contracts/<int:contract_id>/reviews', methods=['GET'])
def get_contract_reviews(contract_id):
    """Get all reviews for a contract"""
    reviews = ReviewResult.query.filter_by(contract_id=contract_id).all()
    return jsonify([review.to_dict() for review in reviews])

@contract_bp.route('/reviews/<int:review_id>', methods=['GET'])
def get_review(review_id):
    """Get a specific review"""
    review = ReviewResult.query.get_or_404(review_id)
    review_dict = review.to_dict()
    
    # Parse findings JSON
    try:
        review_dict['findings'] = json.loads(review.findings)
    except json.JSONDecodeError:
        review_dict['findings'] = review.findings
    
    return jsonify(review_dict)

