import os
import requests
import json
import re
import anthropic

from dotenv import load_dotenv
load_dotenv()
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
ANTHROPIC_MODEL = os.getenv("ANTHROPIC_MODEL", "claude-3-5-haiku-latest")

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "Qwen/Qwen3-Next-80B-A3B-Instruct")
OPENAI_URL = os.getenv("OPENAI_URL", "https://api.deepinfra.com/v1/openai")

# Initialize Claude client
claude_client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)

llm_model = os.getenv("GENAI_ENGINE", "claude")
claude_model = ANTHROPIC_MODEL

from openai import OpenAI
# Create an OpenAI client with your token and endpoint
openai = OpenAI(
    api_key=OPENAI_API_KEY,
    base_url=OPENAI_URL,
)

class TenderPresentationGenerator:
    def __init__(self):
        """
        Initialize the presentation generator.
        """
        print("Initializing presentation generator...")

    def generate_presentation(self, company_info, eligibility_criteria, scope_of_work):
        """
        Generate a professional tender presentation using Claude LLM.
        
        Args:
            company_info (str): Company information including capabilities, experience, etc.
            eligibility_criteria (str): Project eligibility criteria
            scope_of_work (str): Detailed scope of work for the project
            
        Returns:
            str: Complete HTML/CSS presentation code
        """
        
        try:
            # Step 1: Generate presentation content
            print("Step 1: Generating presentation content...")
            content_prompt = self._create_content_prompt(company_info, eligibility_criteria, scope_of_work)
            presentation_content = self._call_claude_api(content_prompt, True)
            
            # Step 2: Parse slides from content
            print("Step 2: Parsing slides...")
            slides = self._parse_slides(presentation_content)
            
            # Step 3: Convert each slide to HTML-CSS
            print("Step 3: Converting slides to HTML-CSS...")
            html_slides = []
            for i, slide_content in enumerate(slides):
                print(f"Processing slide {i+1}/{len(slides)}...")
                html_slide = self._convert_slide_to_html(slide_content, i+1, len(slides))
                html_slides.append(html_slide)
            
            # Step 4: Combine all slides into complete presentation
            print("Step 4: Creating final presentation...")
            complete_presentation = self._create_complete_presentation(html_slides)
            
            return complete_presentation, html_slides, slides, presentation_content
            
        except Exception as e:
            raise Exception(f"Error generating presentation: {str(e)}")

    def _create_content_prompt(self, company_info, eligibility_criteria, scope_of_work):
        """Create a comprehensive prompt for Claude to generate the presentation content."""
        
        prompt = f"""
You are tasked with creating a professional government tender presentation content. 

**IMPORTANT INSTRUCTIONS:**
1. IGNORE the following company information in your presentation: CIN numbers, PAN numbers, director details, turnover details, financial figures
2. FOCUS ONLY on relevant information: past experience, employee capabilities, technical expertise, certifications, and project-relevant competencies
3. Create a 10 slide presentation
4. Ensure content relevance to the project scope
5. Output ONLY the complete presentation content without any additional commentary

**COMPANY INFORMATION:**
{company_info}

**ELIGIBILITY CRITERIA:**
{eligibility_criteria}

**SCOPE OF WORK:**
{scope_of_work}

**REQUIRED SLIDES TO INCLUDE:**
1. Company Overview (capabilities, strengths, relevant expertise only)
2. Project Understanding (demonstrate understanding of the scope)
3. Past Experience (ONLY if relevant experience exists in company info)
4. Implementation Approach (methodology, timeline, deliverables)

**ADDITIONAL SLIDES TO CONSIDER BASED ON PROJECT SCOPE:**
- Technical Capabilities
- Team Structure
- Quality Assurance
- Risk Management
- Support & Maintenance
- Value Proposition

**OUTPUT FORMAT:**
Return ONLY the complete presentation content. Each slide should have:
- Slide Title (use ## for title)
- Bullet points or structured content
- Different slides should be separated by this delimiter: '=============Next Slide============'

**CRITICAL:** 
- Do NOT include any commentary, explanations, or text outside the Presentation slides content
- Make content concise but comprehensive
- Use bullet points and structured format
- Maintain strict relevance to the project scope and eligibility criteria
- This presentation is for first time pitching to the client. It is not for status/progress update. So do not add any progress updates.
"""
        
        return prompt

    def _parse_slides(self, presentation_content):
        """Parse the presentation content into individual slides."""
        slides = presentation_content.split('=============Next Slide============')
        # Clean up slides and remove empty ones
        cleaned_slides = []
        for slide in slides:
            slide = slide.strip()
            if slide and len(slide) > 10:  # Ensure slide has meaningful content
                cleaned_slides.append(slide)
        return cleaned_slides

    def _convert_slide_to_html(self, slide_content, slide_num, total_slides):
        """Convert individual slide content to HTML-CSS formatted slide."""
        
        # Create prompt for HTML conversion
        html_prompt = f"""
Convert the following slide content into beautiful HTML with inline CSS styling. 

**SLIDE CONTENT:**
{slide_content}

**REQUIREMENTS:**
1. Create a single slide div with professional styling
2. Use full screen widescreen layout (16:9 aspect ratio)
3. Use LIGHT, SOOTHING color scheme (soft pastels, light blues, mint greens, cream whites, soft grays)
4. Clean typography with appropriate font sizes
5. Include relevant icons using Unicode symbols (📊 📈 💼 ⚡ 🔧 🎯 ✅ 🏆 👥 📱 💻 🌟 🔒 ⭐ etc.)
6. Use modern card layouts, gradients, and visual elements
7. Make it visually appealing and modern for government presentation
8. Slide should fill entire screen area and the blocks should remain in the center of the screen

**IMPORTANT STYLING NOTES:**
- Use padding: 40px for slide content
- Use soft background gradients
- Include visual icons for bullet points
- Create CSS-based graphics where possible
- Use box-shadows and rounded corners for modern look
- Ensure text is easily readable with good contrast

**OUTPUT:**
Return ONLY the HTML div element with class="slide" and id="slide-{slide_num}" with complete inline CSS styling. No other text or commentary.

**EXAMPLE STRUCTURE:**
<div class="slide" id="slide-{slide_num}">
  <div style="padding: 40px; height: 100%; display: flex; flex-direction: column;">
    <!-- Slide content with lots of icons and visual elements -->
  </div>
</div>
"""
        
        return self._call_claude_api(html_prompt, False)

    def _create_complete_presentation(self, html_slides):
        """Combine all HTML slides into a complete presentation with navigation."""
        
        # Create the complete HTML structure
        html_template = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Government Tender Presentation</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PptxGenJS/3.12.0/pptxgen.bundle.min.js"></script>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}

        body {{
            font-family: 'Inter', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f0f4f8 0%, #e2e8f0 50%, #f7fafc 100%);
            overflow-x: hidden;
            scroll-behavior: smooth;
        }}

        .presentation-container {{
            width: 100%;
            min-height: 100vh;
        }}

        .slide {{
            width: 100vw;
            height: 100vh;
            background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 40px;
            border-bottom: 2px solid #e2e8f0;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            scroll-snap-align: start;
        }}

        html {{
            scroll-snap-type: y mandatory;
        }}

        .slide:nth-child(even) {{
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        }}

        .navigation {{
            position: fixed;
            bottom: 30px;
            right: 30px;
            display: flex;
            flex-direction: column;
            gap: 15px;
            z-index: 1000;
        }}

        .nav-btn {{
            width: 60px;
            height: 60px;
            background: rgba(255, 255, 255, 0.3);
            border: 2px solid rgba(255, 255, 255, 0.5);
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: rgba(71, 85, 105, 0.7);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }}

        .nav-btn:hover {{
            background: rgba(71, 85, 105, 0.9);
            border-color: rgba(71, 85, 105, 0.9);
            color: white;
            transform: scale(1.1);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
        }}

        .nav-btn:disabled {{
            opacity: 0.3;
            cursor: not-allowed;
            transform: none;
        }}

        .nav-btn:disabled:hover {{
            background: rgba(255, 255, 255, 0.3);
            border-color: rgba(255, 255, 255, 0.5);
            color: rgba(71, 85, 105, 0.7);
            transform: none;
        }}

        .slide-counter {{
            position: fixed;
            top: 30px;
            right: 30px;
            background: linear-gradient(135deg, #ddd6fe 0%, #c4b5fd 100%);
            color: #5b21b6;
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: 600;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(139, 92, 246, 0.2);
            font-size: 14px;
            backdrop-filter: blur(10px);
        }}

        .progress-bar {{
            position: fixed;
            top: 0;
            left: 0;
            height: 4px;
            background: linear-gradient(90deg, #10b981, #6ee7b7);
            transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(16, 185, 129, 0.3);
        }}

        .download-btn {{
            position: fixed;
            top: 30px;
            left: 30px;
            background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 25px;
            font-weight: 600;
            cursor: pointer;
            z-index: 1000;
            box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);
            font-size: 14px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }}

        .download-btn:hover {{
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(245, 158, 11, 0.4);
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }}

        /* Global slide styling improvements */
        .slide h1, .slide h2, .slide h3 {{
            color: #1e293b;
            margin-bottom: 20px;
        }}

        .slide p, .slide li {{
            color: #475569;
            line-height: 1.6;
        }}

        /* Smooth scrolling for all elements */
        * {{
            scroll-behavior: smooth;
        }}

        /* Hide scrollbar but keep functionality */
        body::-webkit-scrollbar {{
            width: 8px;
        }}

        body::-webkit-scrollbar-track {{
            background: rgba(0, 0, 0, 0.1);
        }}

        body::-webkit-scrollbar-thumb {{
            background: rgba(16, 185, 129, 0.5);
            border-radius: 4px;
        }}

        body::-webkit-scrollbar-thumb:hover {{
            background: rgba(16, 185, 129, 0.8);
        }}
    </style>
</head>
<body>
    <div class="presentation-container">
        <div class="slide-counter"><span id="current-slide">1</span> / <span id="total-slides">{len(html_slides)}</span></div>
        <div class="progress-bar" id="progress-bar"></div>
        <button class="download-btn" onclick="downloadAsPPTX()">📥 Download PPTX</button>
        
        {chr(10).join(html_slides)}
        
        <div class="navigation">
            <button class="nav-btn" id="prev-btn" onclick="previousSlide()" title="Previous Slide">↑</button>
            <button class="nav-btn" id="next-btn" onclick="nextSlide()" title="Next Slide">↓</button>
        </div>
    </div>

    <script>
        let currentSlide = 1;
        const totalSlides = {len(html_slides)};

        function updateProgress() {{
            const currentSlideEl = document.getElementById('current-slide');
            const progressBar = document.getElementById('progress-bar');
            const prevBtn = document.getElementById('prev-btn');
            const nextBtn = document.getElementById('next-btn');
            
            // Calculate current slide based on scroll position
            const scrollPosition = window.scrollY;
            const slideHeight = window.innerHeight;
            currentSlide = Math.floor(scrollPosition / slideHeight) + 1;
            
            // Ensure slide number is within bounds
            if (currentSlide > totalSlides) currentSlide = totalSlides;
            if (currentSlide < 1) currentSlide = 1;
            
            // Update UI elements
            currentSlideEl.textContent = currentSlide;
            progressBar.style.width = (currentSlide / totalSlides) * 100 + '%';
            
            // Update button states
            prevBtn.disabled = currentSlide === 1;
            nextBtn.disabled = currentSlide === totalSlides;
        }}

        function nextSlide() {{
            if (currentSlide < totalSlides) {{
                const nextSlidePosition = currentSlide * window.innerHeight;
                window.scrollTo({{
                    top: nextSlidePosition,
                    behavior: 'smooth'
                }});
            }}
        }}

        function previousSlide() {{
            if (currentSlide > 1) {{
                const prevSlidePosition = (currentSlide - 2) * window.innerHeight;
                window.scrollTo({{
                    top: prevSlidePosition,
                    behavior: 'smooth'
                }});
            }}
        }}

        // Update progress on scroll
        window.addEventListener('scroll', updateProgress);

        // Keyboard navigation
        document.addEventListener('keydown', function(e) {{
            if (e.key === 'ArrowDown' || e.key === ' ') {{
                e.preventDefault();
                nextSlide();
            }}
            if (e.key === 'ArrowUp') {{
                e.preventDefault();
                previousSlide();
            }}
            if (e.key === 'Home') {{
                e.preventDefault();
                window.scrollTo({{ top: 0, behavior: 'smooth' }});
            }}
            if (e.key === 'End') {{
                e.preventDefault();
                window.scrollTo({{ top: (totalSlides - 1) * window.innerHeight, behavior: 'smooth' }});
            }}
        }});

        // Download as PPTX function
        function downloadAsPPTX() {{
            try {{
                // Create new presentation
                let pptx = new PptxGenJS();
                
                // Get all slides
                const slides = document.querySelectorAll('.slide');
                
                slides.forEach((slide, index) => {{
                    // Add slide to presentation
                    let pptxSlide = pptx.addSlide();
                    
                    // Extract text content from slide
                    const slideTitle = slide.querySelector('h1, h2') ? slide.querySelector('h1, h2').textContent : `Slide ${{index + 1}}`;
                    const slideContent = slide.innerText;
                    
                    // Add title
                    pptxSlide.addText(slideTitle, {{
                        x: 1,
                        y: 1,
                        w: 8,
                        h: 1,
                        fontSize: 24,
                        bold: true,
                        color: '1e293b'
                    }});
                    
                    // Add content (split into manageable chunks)
                    const contentLines = slideContent.split('\\n').filter(line => line.trim() && line !== slideTitle);
                    let yPosition = 2.5;
                    
                    contentLines.forEach((line, lineIndex) => {{
                        if (lineIndex < 15 && yPosition < 6) {{ // Limit lines to fit on slide
                            pptxSlide.addText(line.trim(), {{
                                x: 1,
                                y: yPosition,
                                w: 8,
                                h: 0.3,
                                fontSize: 14,
                                color: '475569'
                            }});
                            yPosition += 0.4;
                        }}
                    }});
                }});
                
                // Save the presentation
                pptx.writeFile({{ fileName: "Government_Tender_Presentation.pptx" }});
                
            }} catch (error) {{
                console.error('Error generating PPTX:', error);
                alert('Error generating PPTX file. Please try again or contact support.');
            }}
        }}

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {{
            updateProgress();
        }});

        // Initialize immediately
        updateProgress();
    </script>
</body>
</html>
"""
        
        return html_template

    def _call_claude_api(self, prompt, is_for_content):
        """Make API call to Claude."""
        if (is_for_content):
            system_message = "You are an expert in creating meaningful professional presentations with relevant content extracted from the information provided."
            temp = 0.3
        else:
            system_message = "You are an expert in creating professional presentations with modern design elements."
            temp = 0.5
        try:
            if llm_model == 'claude':
                response = claude_client.messages.create(
                    model=claude_model,
                    max_tokens=6000,
                    temperature=temp,
                    system=system_message,
                    messages=[
                        {"role": "user", "content": prompt}
                    ]
                )
                response_text = response.content[0].text
            elif llm_model == 'open_llm':
                response = openai.chat.completions.create(
                    model=OPENAI_MODEL,
                    messages=[
                        {"role": "system", "content": system_message},
                        {"role": "user", "content": prompt},
                    ],
                )
                response_text = response.choices[0].message.content
        except Exception as e:
                print(f"Error creating presentation: {str(e)}")
                response_text = "Error creating presentation"
        
        return response_text


# Example usage function
def generate_tender_presentation(company_info, eligibility_criteria, scope_of_work, save_file=False, filename=None):
    """
    Convenience function to generate a tender presentation.
    
    Args:
        company_info (str): Company information
        eligibility_criteria (str): Project eligibility criteria  
        scope_of_work (str): Project scope of work
        save_file (bool): Whether to save the presentation to a file
        filename (str): Output filename if saving
        
    Returns:
        str: Complete HTML/CSS presentation code
    """
    
    generator = TenderPresentationGenerator()
    
    try:
        presentation_html, html_slides, slides, presentation_content = generator.generate_presentation(
            company_info=company_info,
            eligibility_criteria=eligibility_criteria,
            scope_of_work=scope_of_work
        )
        
        if save_file:
            save_filename = filename or "government_tender_presentation.html"
            with open(save_filename, 'w', encoding='utf-8') as f:
                f.write(presentation_html)
            print(f"Presentation saved as {save_filename}")
        
        return presentation_html, html_slides, slides, presentation_content
        
    except Exception as e:
        print(f"Error: {str(e)}")
        return None


#######################################################
# Example usage
#######################################################

# company_info = """
# ABC Technologies Pvt. Ltd.
# CIN: L12345AB2010PTC123456
# PAN: ABCDE1234F

# Our company has 15+ years of experience in software development and digital transformation.
# We have a team of 200+ skilled professionals including:
# - 50 Senior Software Engineers
# - 30 Data Scientists
# - 25 Cloud Architects
# - 20 Project Managers
# - 15 Quality Assurance Engineers

# Certifications: ISO 9001:2015, ISO 27001:2013, CMMI Level 5

# Past Projects:
# - Implemented e-governance solutions for State Government (2019-2022)
# - Developed citizen services portal for Municipal Corporation (2020-2023)  
# - Created digital payment system for Public Distribution System (2021-2024)
# - Built traffic management system for Smart City project (2018-2021)

# Technical Capabilities:
# - Cloud platforms: AWS, Azure, Google Cloud
# - Programming: Java, Python, .NET, React, Angular
# - Databases: Oracle, PostgreSQL, MongoDB
# - DevOps: Docker, Kubernetes, Jenkins, CI/CD
# """

# eligibility_criteria = """
# --- From 17464298405819.pdf (chunk 1) ---\nPre-Qualification Criteria including office in India for minimum 5 years, valid GST registration, average annual turnover of Rs. 5.00 Crore over last 3 years, prior experience of at least two IEC/BCC projects worth minimum Rs. 15 lakh each, not barred/blacklisted, no pending legal proceedings, proven track record in social media campaigns, team expertise in multi-language content development, and submission of all documentary proofs.\n\n--- From 17464298405819.pdf (chunk 2) ---\nLegal Entity requirements, operational in India for at least 5 years, minimum 20 resources manpower, completion of at least two projects each with minimum value of ₹15 lakh for IEC assignments, average annual turnover of Rs. 5.00 Crore or more in last 3 consecutive audited financial years, positive net worth, not blacklisted, no corrupt practices, litigation history disclosure, no joint venture/consortium allowed, MSMEs and startups permitted under Gujarat Procurement Policy\n\n--- From 17464298405819.pdf (chunk 3) ---\nThe Bidder must have an office in India operating for a minimum of the last 5 years. Must have valid GST registration. Should have average annual turnover of Rs. 5.00 Crore or more over the last 3 consecutive financial years (2021-22, 2022-23, and 2023-24). Must demonstrate 2 Project previous experience in handling IEC or BCC activities for rural development or similar government projects. Must furnish detailed team composition. Must not have been barred or blacklisted by any PSU, government department, or private sector entity. No legal proceedings pending. Must have proven track record in managing large-scale social media engagement campaigns. Must have team with expertise in creative content development including multi-language content (Gujarati/Hindi and English). MSMEs and startups are permitted under Gujarat Procurement Policy 2024.\n\n--- From GeM-Bidding-7805326.pdf (chunk 1) ---\nMinimum Average Annual Turnover of the bidder (For 3 Years): 500 Lakh(s); Years of Past Experience Required for same/similar service: 3 Year(s); Past Experience of Similar Services required: Yes; MSE Exemption for Years Of Experience and Turnover: Yes; Startup Exemption for Turnover: Yes; Geographic Presence Required - Office in Gandhinagar or Undertaking for opening the office within one month of the award of the contract; Bidder must have completed 3 major projects in social media management any State or Central Government, local bodies or any PSUs; The minimum average annual financial turnover of the bidder during the last three years, ending on 31st March of the previous financial year, should be as indicated above in the bid document; Years of Past Experience required: The bidder must have experience for number of years as indicated above in bid document (ending month of March prior to the bid opening) of providing similar type of services to any Central / State Govt Organization / PSU; Past Experience of Similar Services: The bidder must have successfully executed/completed similar Services over the last three years.
# """

# scope_of_work = """
# --- From 17464298405819.pdf (chunk 1) ---\nComprehensive scope includes Strategy & Planning, Creative Content Development, Monitoring & Feedback, Social Media Management, and Reports & Documentation. Activities cover IEC and BCC activities for rural development schemes like SBM-G, PMAY-G, MGNREGS across state, district, block and village levels. Includes creative design, social media engagement, dashboard development, content creation in multiple languages, and comprehensive reporting.\n\n--- From 17464298405819.pdf (chunk 2) ---\nSelection of IEC Agency for Designing and Social Media Management Activities under Commissionerate of Rural Development Gujarat, including IEC activities, creative design work, social media management, digital media marketing, content creation for platforms like Facebook, Twitter, Instagram\n\n--- From 17464298405819.pdf (chunk 3) ---\nSelection of IEC agencies to undertake Designing activities under Commissionerate of Rural Development Schemes in the State of Gujarat. The scope includes Information, Education, and Communication (IEC) or Behavior Change Communication (BCC) activities, specifically for rural development projects, social media management activities, creative content development including multi-language content (Gujarati/Hindi and English) tailored for various platforms (digital, print, social media).\n\n--- From GeM-Bidding-7805326.pdf (chunk 1) ---\nItem Category: Hiring of Social Media Agency - Content creation, Content response and content moderation, Response management/Helpdesk support; English, Gujarati, Hindi; Facebook, Twitter, Instagram, WhatsApp, YouTube; Contract Period: 1 Year(s); Core Social Media: Content creation, Content response and content moderation, Response management/Helpdesk support; Language Versions: English, Gujarati, Hindi; Handles Required: Facebook, Twitter, Instagram, WhatsApp, YouTube; Scope of Work/Creative Brief: 1746429513.pdf
# """

# # Generate presentation
# presentation, html_slides, slides, presentation_content = generate_tender_presentation(
#     company_info=company_info,
#     eligibility_criteria=eligibility_criteria,
#     scope_of_work=scope_of_work,
#     save_file=True,
#     filename="government_tender_presentation.html"
# )

# if presentation:
#     print("Presentation generated successfully!")
#     print(f"Total length: {len(presentation)} characters")
#     print("You can now open the HTML file in a browser to view the presentation.")
# else:
#     print("Failed to generate presentation.")