import requests
from bs4 import BeautifulSoup
import ollama
from ai_tool.model.online_ollama_model import OnlineOllamaModel
from ai_tool.model.local_ollama_model import Model, ModelDetails


class ModelManager:
    def __init__ (self):
        self._local_model_list = []
        self._online_model_list = []
        self._omline_modelfile_list = []
        self._modelfiles_baseurl= "https://archive.spacemit.com/spacemit-ai/modelfile/"
        self._models_baseurl= "https://archive.spacemit.com/spacemit-ai/guff/"
    
    @property
    def local_model_list(self):
        return self._local_model_list
    
    @local_model_list.setter
    def local_model_list(self, value):
        """设置 modelName 属性"""
        self._local_model_list = value
    
    @property
    def online_model_list(self):
        return self._online_model_list
    
    @online_model_list.setter
    def online_model_list(self, value):
        """设置 modelName 属性"""
        self._online_model_list = value
    
    @property
    def omline_modelfile_list(self):
        return self._omline_modelfile_list
    
    @omline_modelfile_list.setter
    def omline_modelfile_list(self, value):
        """设置 modelName 属性"""
        self._omline_modelfile_list = value
    
    def get_modelfile_list(self):
        response = requests.get(self.modelfiles_baseurl)
        if response.status_code == 200:
            # 解析HTML内容，提取文件名
            soup = BeautifulSoup(response.content, 'html.parser')
            for link in soup.find_all('a', href=True):
                href = link['href']
                if href.endswith('.modelfile') and href not in self.omline_modelfile_list:
                    self.omline_modelfile_list.append(href)
            return self.omline_modelfile_list
        else:
            print(f"无法获取文件列表，状态码: {response.status_code}")
            return []

    def get_model_from_modelfile(self):
        pass

    def get_online_model_list(self):
        pass

    def update_local_model_list(self):
        for models in ollama.list():
            for model in models[1]:
                # 从 model 字符串中提取名称 (例如: 'qwen2.5-3b:latest' -> 'qwen2.5-3b')
                model_name = model.model.split(':')[0]
                if model_name not in self.local_model_list:
                    self.local_model_list.append(model_name)
        

    def get_uninstalled_model_list(self):
        pass

    def install_models(self):
        pass

    def install_modelfiles(self):
        pass

    def install_model(self):
        pass

