from groq import Groq
from dotenv import load_dotenv
import os
import itertools
import time

load_dotenv()

API_KEYS = os.getenv("GROQ_API_KEYS", "")

# Create an infinite round-robin cycle of API keys
key_cycle = itertools.cycle(API_KEYS)

# Initialize the first client
current_key = next(key_cycle)
client = Groq(api_key=current_key)

def call_groq_chat(messages, model="llama-3.3-70b-versatile", retries=4):
    global client
    for _ in range(retries):
        try:
            response = client.chat.completions.create(
                messages=messages,
                model=model,
                stream=False
            )
            return response.choices[0].message.content
        except Exception as e:
            current_key = next(key_cycle)
            client = Groq(api_key=current_key)
            time.sleep(1)  # optional cooldown
    print("Sorry we had too many requests today, Try in a while please ^-^")


def make_readme(tree):
    return call_groq_chat([
        {
            "role": "user",
            "content": f'''You are an expert technical writer and developer advocate. When given details about a software project, you produce a complete, polished README in Markdown that includes:
                1. Project Title and Badges  
                2. Short Description of the project
                3. Table of Contents  
                4. Features that are implemented in this project: should tell what the project is doing
                5. Prerequisites  
                6. Installation  
                7. Configuration  
                8. Usage Examples  
                9. Running Tests  
                10. Deployment  
                11. Contributing Guidelines  
                12. License  
                13. Contact / Authors

                Your README should use clear headings (`##`,`###`), bullet lists, code blocks, and links where appropriate. Be concise but thorough, and assume the reader has basic command​‑line knowledge.
                Here is the project description:
                {tree}'''
        }
    ])

def make_license():
    return (
        '''Copyright 2025 [Your Name or Organization]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.''')

def make_report(tree):
    return call_groq_chat([
        {
            "role": "user",
            "content": f'''You are an expert technical writer and software documenter. Write a detailed **project report** in **Microsoft Word-compatible format**, not Markdown. 

The report must be structured and equivalent to **6 to 10 MS Word pages**, and include:

1. **Introduction**
   Describe what the project is and what it aims to do, written in paragraph form.

2. **Problem Statement**
   Explain the real-world problem this project solves, and why it's important, in detailed paragraph format.

3. **Project Features**
   - Start with a paragraph introduction.
   - Use bullet points for listing features, followed by paragraphs describing how each feature works (including libraries, modules, and logic).

4. **Flow of Execution**
   - Provide a step-by-step breakdown using paragraphs and bullet points. You may also try drawing a flowchart to show exact working.
   - Pseudocode and diagrams may be described but formatted in plain text (not markdown).

5. **Implementation Details**
   - Explain technologies used (programming languages, frameworks), architecture, key files, APIs, and data sources, all in paragraph format.

6. **Future Scope**
   - Describe potential improvements or expansion plans using paragraphs and, where needed, bullets.

7. **Conclusion**
   - Provide a summary of achievements and impact in paragraph format.

8. **Screenshots / Output Section**
   - Leave placeholders in plain text like: [Insert Screenshot: output.png]

Also include:
- **Tech Stack Used**
- **Libraries and APIs Used**
- **Team Contribution** section explaining who did what.

Avoid any use of Markdown (**, ##, `, etc.) and keep the language professional, like in a formal university project submission or software engineering report.

Project Description:

{tree}'''
        }
    ])