import requests
import json
import logging
import time
from config import NVIDIA_API_KEY, NVIDIA_BASE_URL, NVIDIA_MODEL, SYSTEM_INSTRUCTION, USER_PROMPT_TEMPLATE

# Configure logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def process_article(original_title, original_content):
    """
    Sends the article to NVIDIA NIM API (OpenAI-compatible) to rewrite it and generate a short video script.
    Guarantees structured JSON output using response_format and retries on timeouts.
    """
    if not NVIDIA_API_KEY:
        raise ValueError("NVIDIA_API_KEY is not configured in config.py")

    url = f"{NVIDIA_BASE_URL.rstrip('/')}/chat/completions"
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {NVIDIA_API_KEY}"
    }
    
    user_prompt = USER_PROMPT_TEMPLATE.format(
        original_title=original_title,
        original_content=original_content
    )
    
    payload = {
        "model": NVIDIA_MODEL,
        "messages": [
            {
                "role": "system",
                "content": SYSTEM_INSTRUCTION
            },
            {
                "role": "user",
                "content": user_prompt
            }
        ],
        "temperature": 0.7,
        "max_tokens": 4096,
        "response_format": {"type": "json_object"}
    }
    
    max_retries = 2
    for attempt in range(max_retries):
        try:
            logging.info(f"Sending request to NVIDIA API (Attempt {attempt + 1}/{max_retries}) using model: {NVIDIA_MODEL}...")
            response = requests.post(url, headers=headers, json=payload, timeout=30)
            response.raise_for_status()
            
            response_data = response.json()
            
            choices = response_data.get("choices", [])
            if not choices:
                logging.error(f"No response choices returned from NVIDIA API. Full response: {response_data}")
                return None
                
            message_content = choices[0].get("message", {}).get("content", "").strip()
            if not message_content:
                logging.error("No message content found in choice.")
                return None
                
            # Parse the JSON string from the response
            processed_data = json.loads(message_content)
            return processed_data
            
        except requests.exceptions.Timeout as t_err:
            logging.warning(f"Timeout occurred on attempt {attempt + 1}: {t_err}")
            if attempt < max_retries - 1:
                logging.info("Retrying in 2 seconds...")
                time.sleep(2)
            else:
                logging.error("Max retries reached. Skipping article due to API timeout.")
        except requests.exceptions.HTTPError as http_err:
            logging.error(f"NVIDIA API HTTP Error: {http_err} - Response: {response.text}")
            return None
        except json.JSONDecodeError as json_err:
            logging.error(f"Failed to parse JSON from NVIDIA response: {json_err}. Raw text: {message_content if 'message_content' in locals() else 'None'}")
            return None
        except Exception as e:
            logging.error(f"Unexpected error in process_article: {e}")
            return None
    return None
