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
    raise RuntimeError(
        "No GROQ API key provided. Use --api-key or set GROQ_API_KEY in your environment."
    )


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...
Project Description:
{tree}'''
        }
    ])


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

Permission is hereby granted...'''
    )


def make_report(tree):
    return call_groq_chat([
        {
            "role": "user",
            "content": f'''You are an expert technical writer...Project Description:
{tree}'''
        }
    ])