import requests
from typing import Dict, Any

class AuthManager:
    def __init__(self, url: str, db: str, username: str, api_key: str):
        self.url = url
        self.db = db
        self.username = username
        self.api_key = api_key
        self.uid = None
        self.session_id = None

    def login(self) -> bool:
        login_url = f"{self.url}/web/session/authenticate"
        login_data = {
            "jsonrpc": "2.0",
            "params": {
                "db": self.db,
                "login": self.username,
                "password": self.api_key
            }
        }
        response = requests.post(login_url, json=login_data)
        result = response.json()
        
        if result.get("error"):
            print(f"Erreur de connexion: {result['error']['message']}")
            return False
        
        self.uid = result.get("result", {}).get("uid")
        self.session_id = response.cookies.get("session_id")
        return bool(self.uid)

    def _rpc_call(self, endpoint: str, params: Dict[str, Any]) -> Dict[str, Any]:
        full_url = f"{self.url}{endpoint}"
        headers = {"Content-Type": "application/json"}
        data = {"jsonrpc": "2.0", "method": "call", "params": params}
        
        response = requests.post(full_url, json=data, headers=headers, cookies={"session_id": self.session_id})
        return response.json().get("result", {})
