"""Database manager implementation for LSCSIM."""

from __future__ import annotations

from pathlib import Path
from typing import Any

from pytola_sim.lscsim.dbmanage import (
    MATERIAL_TABLE_COLUMNS,
    PRODUCT_TABLE_COLUMNS,
    SIMULATION_TABLE_COLUMNS,
    DatabaseManager,
)
from pytola_sim.lscsim.utils.logger import get_logger

logger = get_logger(__name__)


class LSCSIMDatabaseManager:
    """Enhanced database manager specifically for LSCSIM."""

    def __init__(self, database_path: Path | None = None) -> None:
        if database_path is None:
            database_path = Path.home() / "LSCSIM_Data" / "lscsim.db"

        database_url = f"sqlite:///{database_path}"
        self.db_manager = DatabaseManager(database_url)
        self._initialize_tables()
        logger.info("LSCSIM database manager initialized")

    def _initialize_tables(self) -> None:
        """Initialize standard LSCSIM tables."""
        # Create product table
        self.db_manager.create_table("products", PRODUCT_TABLE_COLUMNS)

        # Create simulation table
        self.db_manager.create_table("simulations", SIMULATION_TABLE_COLUMNS)

        # Create material table
        self.db_manager.create_table("materials", MATERIAL_TABLE_COLUMNS)

        logger.info("Standard LSCSIM tables initialized")

    def add_product(self, product_data: dict[str, Any]) -> int | None:
        """Add a new product to the database."""
        return self.db_manager.insert_record("products", product_data)

    def get_products(self, filters: dict[str, Any] | None = None) -> list[dict[str, Any]]:
        """Get products from database."""
        return self.db_manager.query_records("products", filters)

    def update_product(self, product_id: int, data: dict[str, Any]) -> bool:
        """Update product information."""
        return self.db_manager.update_record("products", product_id, data)

    def delete_product(self, product_id: int) -> bool:
        """Delete a product."""
        return self.db_manager.delete_record("products", product_id)

    def add_simulation(self, simulation_data: dict[str, Any]) -> int | None:
        """Add a new simulation record."""
        return self.db_manager.insert_record("simulations", simulation_data)

    def get_simulations(self, filters: dict[str, Any] | None = None) -> list[dict[str, Any]]:
        """Get simulation records."""
        return self.db_manager.query_records("simulations", filters)

    def update_simulation(self, simulation_id: int, data: dict[str, Any]) -> bool:
        """Update simulation record."""
        return self.db_manager.update_record("simulations", simulation_id, data)

    def add_material(self, material_data: dict[str, Any]) -> int | None:
        """Add a new material to the database."""
        return self.db_manager.insert_record("materials", material_data)

    def get_materials(self, filters: dict[str, Any] | None = None) -> list[dict[str, Any]]:
        """Get materials from database."""
        return self.db_manager.query_records("materials", filters)

    def get_material_by_name(self, name: str) -> dict[str, Any] | None:
        """Get material by name."""
        materials = self.get_materials({"material_name": name})
        return materials[0] if materials else None

    def backup_database(self, backup_directory: Path) -> bool:
        """Create database backup."""
        backup_path = backup_directory / f"lscsim_backup_{self._get_timestamp()}.db"
        return self.db_manager.backup_database(backup_path)

    def get_database_info(self) -> dict[str, Any]:
        """Get comprehensive database information."""
        info = {
            "tables": {},
            "total_records": 0,
        }

        for table_name in self.db_manager.list_tables():
            table_info = self.db_manager.get_table_info(table_name)
            if table_info:
                info["tables"][table_name] = table_info
                info["total_records"] += table_info["record_count"]

        return info

    def _get_timestamp(self) -> str:
        """Get current timestamp for backup naming."""
        from datetime import datetime, timezone

        return datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")

    def close(self) -> None:
        """Close database connections."""
        self.db_manager.close()
