# Copyright 2025-present Erioon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Visit www.erioon.com/dev-docs for more information about the python SDK

import json
from erioon.collection import Collection
import requests

class Database:
    def __init__(self, user_id, metadata, database=None, cluster=None, access_type=None, sas_url=None, base_url="https://sdk.erioon.com"):
        """
        Initialize a Database instance.

        Args:
            user_id (str): The ID of the authenticated user.
            metadata (dict): Metadata containing information about the database and its collections.
            database (str, optional): The name or identifier of the database.
            cluster (str, optional): The cluster where the database is hosted.
            sas_url (str, optional): SAS URL for accessing storage container.
        """
        self.base_url = base_url
        self.user_id = user_id
        self.metadata = metadata
        self.db_id = metadata.get("database_info", {}).get("_id")
        self.database = database
        self.cluster = cluster
        self.access_type = access_type
        self.sas_url = sas_url

    def __getitem__(self, collection_id):
        """
        Enables dictionary-like access to collections within the database.

        Args:
            collection_id (str): Identifier of the collection to retrieve.

        Returns:
            Collection: An instance of the Collection class initialized with metadata.
            str: Error message if the collection is not found.
        """
        
        coll_meta = None
        collections = self.metadata.get("database_info", {}).get("collections", {})
        if collection_id.startswith("coll-"):
            coll_meta = collections.get(collection_id)
            coll_status = coll_meta.get("status")
            if coll_status == "active":
                coll_id = collection_id
            else:
                raise Exception(f'[ErioonClient] Collection "{collection_id}" is not available')
        else:
            for col_id in collections:
                coll_name = collections[col_id].get("coll_name")
                coll_status = collections[col_id].get("status")
                if coll_name == collection_id:
                    if coll_status == "active":
                        coll_meta = collections[col_id]
                        coll_id = col_id
                    else:
                        raise Exception(f'[ErioonClient] Collection "{collection_id}" is not available')

        if not coll_meta:
            raise Exception("[ErioonClient] No collection found")

        return Collection(
            user_id=self.user_id,
            db_id=self.db_id,
            coll_id=coll_id,
            metadata=coll_meta,
            database=self.database,
            cluster=self.cluster,
            access_type= self.access_type,
            sas_url=self.sas_url
        )
        
    def create_collection(self, collection_name, collection_desc):
        """
        Creates a new collection inside a given database.

        """
        payload = {
            "user_id": self.user_id,
            "db_id": self.db_id,
            "coll_name": collection_name,
            "coll_desc": collection_desc,
        }
        
        try:
            response = requests.post(
                f"{self.base_url}/create_coll_sdk",
                json=payload,
                headers={"Content-Type": "application/json"}
            )

            if response.status_code == 200:
                print(f"Collection '{collection_name}' created successfully!")
                return collection_name
            else:
                raise Exception(f"[ErioonClient] Collection creation failed: {response.text}")

        except requests.exceptions.RequestException as e:
            print(f"Collection create request failed: {str(e)}")

    def __str__(self):
        """
        Returns a nicely formatted JSON string of the database metadata.
        Useful for debugging and inspecting the database info.

        Returns:
            str: Pretty-printed JSON metadata.
        """
        return json.dumps(self.metadata, indent=4)

    def __repr__(self):
        """
        Returns a concise, informative string representation of the Database instance.

        Returns:
            str: Formatted string showing the database ID, cluster, and database name.
        """
        return f"<Database db_id={self.db_id}, cluster={self.cluster}, database={self.database}>"
