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

load_dotenv()

# User-provided API key (set via CLI)
USER_API_KEY = None

def set_api_key(key: str):
    """
    Allows CLI to inject an API key, avoiding interactive prompt.
    """
    global USER_API_KEY
    USER_API_KEY = key.strip()

# Lazy Groq client
_client = None

def _get_api_key():
    """
    Determine which API key to use, in order of priority:
    1) CLI-injected USER_API_KEY
    2) Environment variable GROQ_API_KEY
    """
    if USER_API_KEY:
        return USER_API_KEY
    env_key = os.getenv("GROQ_API_KEY", "").strip()
    if env_key:
        return env_key
    print("Please set your GROQ API key in the .env file or via the --api-key CLI option.")


def _get_client():
    """Instantiate or return existing Groq client"""
    global _client
    if _client is None:
        api_key = _get_api_key()
        _client = Groq(api_key=api_key)
    return _client


def call_groq_chat(messages, model="llama-3.3-70b-versatile", retries=3):
    """
    Send `messages` to Groq, retrying once on error by re-instantiating client.
    """
    global _client
    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 on next loop
                _client = None
                time.sleep(1)
                continue
            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 [Year] [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}
'''
        }
    ])