#!/usr/bin/env python3
"""
Check OpenCode Zen model prices and print free models
"""
import requests
from bs4 import BeautifulSoup
import logging
import sys

# ANSI escape codes for styling
GRAY_ITALIC = "\033[3;90m"  # Italic + bright black (light gray)
RESET = "\033[0m"

logger = logging.getLogger(__name__)

ZEN_DOCS_URL = "https://opencode.ai/docs/zen"
ZEN_MODELS_API_URL = "https://opencode.ai/zen/v1/models"


def fetch_zen_data():
    """
    Fetch and parse OpenCode Zen documentation for pricing
    
    Returns:
        list: List of free model dictionaries
    """
    try:
        logger.info(f"Fetching Zen documentation from {ZEN_DOCS_URL}...")
        response = requests.get(ZEN_DOCS_URL, timeout=30)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, 'html.parser')
        tables = soup.find_all('table')
        
        if not tables:
            logger.error("No tables found in Zen documentation")
            return []

        # First table usually contains Model -> Model ID mapping
        # Second table usually contains Pricing
        
        model_to_id = {}
        free_models = []
        
        for table in tables:
            headers = [th.get_text(strip=True) for th in table.find_all('th')]
            rows = table.find_all('tr')[1:] # Skip header
            
            if 'Model ID' in headers:
                model_idx = headers.index('Model')
                id_idx = headers.index('Model ID')
                for row in rows:
                    cols = row.find_all('td')
                    if len(cols) > max(model_idx, id_idx):
                        model_name = cols[model_idx].get_text(strip=True)
                        model_id = cols[id_idx].get_text(strip=True)
                        model_to_id[model_name] = model_id
            
            if 'Input' in headers and 'Output' in headers:
                model_idx = headers.index('Model')
                input_idx = headers.index('Input')
                output_idx = headers.index('Output')
                
                for row in rows:
                    cols = row.find_all('td')
                    if len(cols) > max(model_idx, input_idx, output_idx):
                        model_name = cols[model_idx].get_text(strip=True)
                        input_price = cols[input_idx].get_text(strip=True)
                        output_price = cols[output_idx].get_text(strip=True)
                        
                        if input_price.lower() == 'free' and output_price.lower() == 'free':
                            free_models.append({
                                'name': model_name,
                                'input': input_price,
                                'output': output_price,
                                'id': model_to_id.get(model_name, "Unknown")
                            })

        return free_models

    except Exception as e:
        logger.error(f"Error fetching Zen data: {e}")
        return []


def print_free_models(free_models):
    """
    Print free models in a readable format
    
    Args:
        free_models: List of free model dictionaries
    """
    if not free_models:
        print("No free Zen models found.")
        return

    print(f"\nFound {len(free_models)} free Zen models:\n")
    print("-" * 80)
    
    for i, model in enumerate(free_models, 1):
        mid = model.get('id', 'Unknown')
        # Print just the number and ID
        print(f"{i}. {mid}")
        
    print("-" * 80)


def main():
    """
    Main function to fetch and display free Zen models
    """
    logging.basicConfig(level=logging.WARNING)
    
    free_models = fetch_zen_data()
    print_free_models(free_models)


if __name__ == "__main__":
    main()
