import os
import cohere
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

def get_cohere_client():
    api_key = os.getenv("COHERE_API_KEY")
    if not api_key:
        raise RuntimeError("COHERE_API_KEY not found in environment")
    return cohere.Client(api_key)

def parse_funding_text(text: str, co: cohere.Client) -> str:
    prompt = (
        "You are an expert in funding data extraction.\n\n"
        "Extract the funding information from the following text and return *only* valid JSON. "
        "Do not add any explanation or preamble.\n\n"
        "Required JSON keys:\n"
        "- funder_name\n"
        "- funding_amount (can be null)\n"
        "- currency (can be null)\n"
        "- program_name (can be null)\n"
        "- grant_period (can be null)\n\n"
        f"Text:\n{text}\n\n"
        "Respond with JSON only. No explanation, no markdown formatting."
    )

    try:
        response = co.generate(
            model="command-r-plus",
            prompt=prompt,
            temperature=0.2,
            max_tokens=300,
        )
        return response.generations[0].text.strip()
    except Exception as e:
        raise RuntimeError(f"Funding parsing failed: {str(e)}")
