import requests
import json

class AnkhDB:
    def __init__(self, api_key, base_url="http://localhost:5000", token=None):
        self.api_key = api_key
        self.base_url = base_url
        self.token = token

    @property
    def headers(self):
        h = {
            "Content-Type": "application/json",
            "x-api-key": self.api_key
        }
        if self.token:
            h["Authorization"] = f"Bearer {self.token}"
        return h

    def _raw_request(self, path, method="GET", body=None):
        url = f"{self.base_url}{path}"
        response = requests.request(method, url, headers=self.headers, json=body)
        
        if response.ok:
            return response.json()
        else:
            raise Exception(f"Error {response.status_code}: {response.text}")

    # Auth Methods
    def login(self, email, password):
        data = self._raw_request("/api/auth/login", method="POST", body={"email": email, "password": password})
        if "token" in data:
            self.token = data["token"]
        return data

    def register(self, email, password):
        data = self._raw_request("/api/auth/register", method="POST", body={"email": email, "password": password})
        if "token" in data:
            self.token = data["token"]
        return data

    def logout(self):
        res = self._raw_request("/api/auth/logout", method="POST")
        self.token = None
        return res

    # DB Methods
    def from_collection(self, collection):
        return AnkhQuery(self, collection)

class AnkhQuery:
    def __init__(self, client, collection):
        self.client = client
        self.collection = collection

    def select(self):
        return self.client._raw_request(f"/db/{self.collection}")

    def insert(self, data):
        return self.client._raw_request(f"/db/{self.collection}", method="POST", body=data)

    def get(self, doc_id):
        return self.client._raw_request(f"/db/{self.collection}/{doc_id}")

    def update(self, doc_id, data):
        return self.client._raw_request(f"/db/{self.collection}/{doc_id}", method="PUT", body=data)

    def delete(self, doc_id):
        return self.client._raw_request(f"/db/{self.collection}/{doc_id}", method="DELETE")
