# src/autodocz/generator.py

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


API_KEY = input("Please enter your GROQ API key (get one at https://console.groq.com/keys): ").strip()
if not API_KEY:
    raise RuntimeError("No API key provided. Aborting.")

# 3) Prepare a single client (will be re-instantiated on failure)
_client = None

def _get_client():
    global _client
    if _client is None:
        _client = Groq(api_key=API_KEY)
    return _client

def call_groq_chat(messages, model="llama-3.3-70b-versatile", retries=3):
    """
    Send `messages` to the Groq chat endpoint, retrying on any exception
    by re-instantiating the client once.
    """
    for attempt in range(retries):
        try:
            client = _get_client()
            resp = client.chat.completions.create(
                messages=messages,
                model=model,
                stream=False
            )
            return resp.choices[0].message.content
        except Exception as e:
            if attempt < retries - 1:
                # teardown & recreate the client, just in case
                _client = Groq(api_key=API_KEY)
                time.sleep(1)
                continue
            # final failure
            raise RuntimeError(f"Groq API failed after {retries} attempts: {e}")

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  
5. Prerequisites  
6. Installation  
7. Configuration  
8. Usage Examples  
9. Running Tests  
10. Deployment  
11. Contributing Guidelines  
12. License  
13. Contact / Authors

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...
'''
    )

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 format (no Markdown tags). It should be 6–10 pages, covering:

1. Introduction  
2. Problem Statement  
3. Project Features  
4. Flow of Execution  
5. Implementation Details  
6. Future Scope  
7. Conclusion  
8. Screenshots / Outputs [placeholders]

Also include Tech Stack, Libraries/APIs, and Team Contribution.

Project Description:
{tree}
'''
        }
    ])
