# ahaat/core.py

import json
import requests

api = "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"

def clean_output(text: str) -> str:
    """
    Removes:
    - wrapping single/double quotes
    - code fences ```...```
    - leading/trailing whitespace
    """
    text = text.strip()

    # remove wrapping quotes
    if (text.startswith('"') and text.endswith('"')) or \
       (text.startswith("'") and text.endswith("'")):
        text = text[1:-1]

    # remove markdown code fences
    if text.startswith("```") and text.endswith("```"):
        # remove first ```... and last ```
        text = "\n".join(text.split("\n")[1:-1])

    return text.strip()


def format_markdown(text: str) -> str:
    """
    Fix common markdown issues:
    - Removes extra blank lines
    - Trims trailing spaces
    """
    lines = text.split("\n")

    cleaned = []
    previous_blank = False

    for line in lines:
        stripped = line.rstrip()

        # Remove double blank lines
        if stripped == "":
            if previous_blank:
                continue
            previous_blank = True
        else:
            previous_blank = False

        cleaned.append(stripped)

    return "\n".join(cleaned)

def generate(prompt):
    r = requests.post(
        "https://api.groq.com/openai/v1/chat/completions",
        headers={"Authorization": f"Bearer {api}"},
        json={
            "model": "llama-3.3-70b-versatile",
            "messages": [{"role": "user", "content": prompt}]
        }
    )

    if r.status_code != 200:
        return f"[GROQ ERROR {r.status_code}]\n{r.text}"

    data = r.json()

    if "error" in data:
        return f"[GROQ ERROR]\n{json.dumps(data['error'], indent=2)}"

    try:
        text = data["choices"][0]["message"]["content"]
    except Exception:
        return f"[INVALID RESPONSE]\n{json.dumps(data, indent=2)}"

    text = clean_output(text)
    text = format_markdown(text)

    return text
