from services.ai_service import AIService
from typing import Dict, Any


class OfferLetterService:
    def __init__(self):
        """Initialize the offer letter service with AI service"""
        self.ai_service = AIService()
    
    def generate_offer_letter(self, candidate_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        Generate an offer letter using AI based on provided candidate and job information
        
        Args:
            candidate_data: Dictionary containing candidate and job information
            
        Returns:
            Dict containing success status and either offer_letter or error message
        """
        try:
            # Validate required fields
            required_fields = ['candidate_name', 'job_title', 'company_name', 'start_date', 'salary']
            missing_fields = []
            
            for field in required_fields:
                if not candidate_data.get(field, '').strip():
                    missing_fields.append(field)
            
            if missing_fields:
                return {
                    "success": False,
                    "error": f"Required fields missing: {', '.join(missing_fields)} are mandatory"
                }
            
            # Create AI prompt for offer letter generation
            system_prompt = """
You are a professional HR assistant specialized in creating formal offer letters. 
Generate a professional, warm, and comprehensive offer letter using ONLY the provided information.
Do NOT include any placeholder text like [Your Company Letterhead], [Your Contact Information], [Date], [Address], etc.
Start directly with the greeting and use only the actual data provided.
The letter should be clean, professional, and contain only real information.
"""
            
            user_prompt = self._build_user_prompt(candidate_data)
            
            # Generate offer letter using AI service
            offer_letter = self.ai_service.ai_response(
                question=user_prompt,
                system_prompt=system_prompt,
                max_tokens=2000
            )
            
            if not offer_letter or offer_letter.strip() == "":
                return {
                    "success": False,
                    "error": "Failed to generate offer letter - AI service returned empty response"
                }
            
            # Check if AI returned an error
            if offer_letter.startswith("Error:"):
                return {
                    "success": False,
                    "error": f"AI service error: {offer_letter}"
                }
            
            return {
                "success": True,
                "offer_letter": offer_letter.strip()
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"Error generating offer letter: {str(e)}"
            }
    
    def _build_user_prompt(self, candidate_data: Dict[str, Any]) -> str:
        """
        Build the user prompt for AI offer letter generation
        
        Args:
            candidate_data: Dictionary containing candidate and job information
            
        Returns:
            Formatted user prompt string
        """
        # Set defaults for optional fields
        department = candidate_data.get('department', '').strip() or "Not specified"
        employment_type = candidate_data.get('employment_type', '').strip() or "Full-time"
        benefits = candidate_data.get('benefits', '').strip() or "Standard company benefits package"
        
        user_prompt = f"""
Generate a professional offer letter with the following details:

Candidate Name: {candidate_data['candidate_name']}
Job Title: {candidate_data['job_title']}
Department: {department}
Company Name: {candidate_data['company_name']}
Start Date: {candidate_data['start_date']}
Salary: {candidate_data['salary']}
Employment Type: {employment_type}
Benefits: {benefits}

CRITICAL INSTRUCTIONS:
1. Start directly with "Dear {candidate_data['candidate_name']}," - NO letterhead, addresses, or placeholder text
2. DO NOT include [Your Company Letterhead], [Date], [Your Contact Information], [Address], [Acceptance Deadline], or ANY text in brackets []
3. Express pleasure in offering the position from {candidate_data['company_name']}
4. Clearly state the job title, department (if not "Not specified"), salary, and start date
5. Include employment type and benefits information
6. DO NOT use "Warm regards", "Sincerely", [Your Name], [Your Title], or any signature blocks
7. End ONLY with "Please review the offer and confirm your decision below." - NO additional text after this
8. Use ONLY the actual data provided - NO placeholder text, NO brackets [], NO [Date], NO [Acceptance Deadline Date]
9. Be professional and direct
10. Generate only the clean offer letter content - NO signature, NO closing formalities

Please generate the offer letter using ONLY the real data provided.
"""
        
        return user_prompt
    
    