import requests
import os
from typing import List, Dict
from .base import FetchBase

class FetchIFlow(FetchBase):
    """IFlow model list fetcher"""
    
    @property
    def provider(self) -> str:
        return "iflow"

    def fetch_models(self) -> List[str]:
        """
        Fetch model list from IFlow
        """
        url = "https://iflow.cn/api/platform/models/list"
        
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "Content-Type": "application/json",
            # "Cookie": "..." # Tested, this interface does not require Cookie to access
        }
        
        payload = {} 

        try:
            # POST request
            response = requests.post(url, json=payload, headers=headers, timeout=30)
            
            response.raise_for_status()
            data = response.json()
            
            models = []
            
            if isinstance(data, dict) and "data" in data and isinstance(data["data"], dict):
                for category, model_list in data["data"].items():
                    if isinstance(model_list, list):
                        for model in model_list:
                            if isinstance(model, dict):
                                # Prioritize using modelName, if not available try other fields
                                model_name = model.get("modelName") or model.get("showName") or model.get("id")
                                if model_name:
                                    models.append(str(model_name))
            
            return models

        except requests.exceptions.RequestException as e:
            return self._handle_http_error(e)
