import requests
import base64
import json
from typing import Optional, Dict, List
import os
from dotenv import load_dotenv

load_dotenv()
BASE_URL = "http://localhost:8080"

class APIClient:
    def __init__(self, base_url: Optional[str] = None):
        self.base_url = BASE_URL
        self.token = None
        self.session = requests.Session()
    
    def login(self, username: str, password: str) -> bool:
        try:
            response = self.session.post(
                f"{self.base_url}/oauth/authenticate/",
                json={"username": username, "password": password}
            )
            response.raise_for_status()
            
            data = response.json()
            print(data)
            
            self.token = data.get("data").get("access_token")
            self.refresh_token = data.get("data").get("refresh_token")
            print(self.token)
            
            if self.token:
                self.session.headers.update({
                    "Authorization": f"Bearer {self.token}",
                    "Content-Type": "application/json"
                })
                return True
            return False
            
        except requests.exceptions.RequestException as e:
            print(f"Erreur de connexion: {e}")
            return False


    def publish_document(self, file_path: str, folder: str = "default") -> bool:
        try:
            # Vérifier si le fichier existe
            if not os.path.exists(file_path):
                print(f"Error: The file {file_path} does not exist")
                return False
            
            # Vérifier l'extension
            if not file_path.endswith('.md') and not file_path.endswith('.smd'):
                print("Error: The file must have the extension .md / .smd")
                return False
            
            # Lire et encoder le fichier
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            encoded_content = base64.b64encode(content.encode('utf-8')).decode('utf-8')
            filename = os.path.basename(file_path)
            
            # Envoyer au serveur
            payload = {
                "filename": filename,
                "data": encoded_content,
            }
            print(payload)
            
            response = self.session.post(
                f"{self.base_url}/api/space/upload-publication/",
                json=payload
            )
            response.raise_for_status()
            
            print(f"Document {filename} successfully published")
            return True
            
        except requests.exceptions.RequestException as e:
            print(f"Error during the publish process: {e}")
            return False
        except Exception as e:
            print(f"Unexpected error: {e}")
            return False
    
    def list_documents(self, folder: Optional[str] = "space") -> List[Dict]:
        model = "space"
        try:
            params = {}
            if folder:
                params['space'] = folder
            

            
            if folder != None:
                model = "publication"
            

            payload = {
                "query" : "",
                "model" : model,
                "type" : "",
                "parent" : folder,
            }

            if model == "publication" : 
                response = self.session.post(
                    f"{self.base_url}/api/space/get-space/",
                    params=params,
                    json=payload
                )
                response.raise_for_status()
                data = response.json().get("data")
            else:
                if payload["parent"] == None:
                    payload["parent"] = "-"
                response = self.session.post(
                    f"{self.base_url}/api/space/search-model/",
                    params=params,
                    json=payload
                )
                response.raise_for_status()
                data = response.json().get("data").get("owned")
            
            return data
            
        except requests.exceptions.RequestException as e:
            print(f"Error retrieving documents: {e}")
            return []