import logging
import sys
import traceback
from datetime import datetime, timezone

from .connection import FOpensearchConnection


class FOpensearchHandler(logging.Handler):
    def __init__(
        self,
        connection_adapter: FOpensearchConnection,
        index="logs",
        tenant_id="tenant_id",
    ):
        """
        connection_adapter: instance of custom_logger.connections.opensearch_connection.OpenSearchConnection
        index_prefix: prefix for indexes (tenant_id will be appended dynamically)
        tenant_field: field name in record.extra used for tenant-based indexing
        """
        super().__init__()
        self.connection_adapter = connection_adapter
        self.index_prefix = index
        self.tenant_field = tenant_id
        self._index_checked = False  # flag for lazy index creation

    def _ensure_index(self, client, index_name):
        try:
            mappings = {
                "mappings": {
                    "properties": {
                        "created_at": {"type": "date"},
                        "level": {"type": "keyword"},
                        "message": {"type": "text"},
                        "logger": {"type": "keyword"},
                        "module": {"type": "keyword"},
                        "tenant_id": {"type": "text"},
                    }
                }
            }
            if not self._index_checked:
                if not client.indices.exists(index=index_name):
                    # minimal mapping, you can expand later
                    client.indices.create(index=index_name, body=mappings)
                    self._index_checked = True
        except Exception as e:
            raise RuntimeError(f"Not able to create Index: {e}")

    def _resolve_index(self, record, tenant_id: str):
        return f"{self.index_prefix}_{tenant_id}"

    def emit(self, record: logging.LogRecord):
        try:
            msg = self.format(record)
            # index_name = self._resolve_index(record)

            doc = {
                "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
                "level": record.levelname,
                "module": record.module,
                "message": msg,
            }
            extra = getattr(record, "extra", None)
            if extra:
                rec = extra.__dict__
                for k, v in rec.items():
                    doc[k] = v

            tenantid = doc["tenant_id"]
            index_name = self._resolve_index(doc, tenantid.lower())
            client = self.connection_adapter.connect()
            self._ensure_index(client, index_name)
            client.index(index=index_name, body=doc)

        except Exception as e:
            print(f"FOpensearchHandler Error: {e}", file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
