import os
import sys
import time
import subprocess
import logging
from dotenv import load_dotenv
from sqlalchemy import create_engine, text
from sqlalchemy.orm import declarative_base, sessionmaker, scoped_session

# Load .env
load_dotenv(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env'))
load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'))

logger = logging.getLogger(__name__)

# Default XAMPP MySQL credentials
MYSQL_USER = os.environ.get("MYSQL_USER", "root")
MYSQL_PASSWORD = os.environ.get("MYSQL_PASSWORD", "")
MYSQL_HOST = os.environ.get("MYSQL_HOST", "127.0.0.1")
MYSQL_PORT = int(os.environ.get("MYSQL_PORT", 3307))
MYSQL_DB = os.environ.get("MYSQL_DB", "cloudvault")

DATABASE_URL = os.environ.get("DATABASE_URL", "")

def is_mysql_reachable(host, port, user, password, db=None, timeout=2):
    try:
        import pymysql
        conn = pymysql.connect(
            host=host,
            user=user,
            password=password,
            port=int(port),
            database=db,
            connect_timeout=timeout
        )
        conn.close()
        return True
    except Exception:
        return False

def try_auto_start_xampp_mysql():
    """Attempts to auto-launch XAMPP MySQL if executable exists on Windows"""
    xampp_mysqld = r"C:\xampp\mysql\bin\mysqld.exe"
    xampp_ini = r"C:\xampp\mysql\bin\my.ini"
    if os.path.exists(xampp_mysqld) and os.path.exists(xampp_ini):
        try:
            print("[INFO] Attempting to auto-start XAMPP MySQL daemon...")
            subprocess.Popen(
                [xampp_mysqld, f"--defaults-file={xampp_ini}", "--standalone"],
                cwd=r"C:\xampp",
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL
            )
            time.sleep(2)
            return True
        except Exception as e:
            logger.warning(f"Failed to auto-start XAMPP MySQL: {e}")
    return False

# Smart MySQL resolution
is_mysql = "mysql" in DATABASE_URL.lower() or os.environ.get("DB_ENGINE") == "mysql"

if is_mysql:
    # 1. Check if configured port (3307) is reachable
    reachable = is_mysql_reachable(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD)

    # 2. If not reachable, check port 3306 (standard MySQL port)
    if not reachable and MYSQL_PORT != 3306:
        if is_mysql_reachable(MYSQL_HOST, 3306, MYSQL_USER, MYSQL_PASSWORD):
            MYSQL_PORT = 3306
            reachable = True

    # 3. If still not reachable, try to auto-start XAMPP MySQL
    if not reachable:
        try_auto_start_xampp_mysql()
        reachable = is_mysql_reachable(MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD)
        if not reachable and MYSQL_PORT != 3306:
            if is_mysql_reachable(MYSQL_HOST, 3306, MYSQL_USER, MYSQL_PASSWORD):
                MYSQL_PORT = 3306
                reachable = True

    if reachable:
        DATABASE_URL = f"mysql+pymysql://{MYSQL_USER}:{MYSQL_PASSWORD}@{MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}?charset=utf8mb4"
        print(f"[DATABASE] Connected to XAMPP MySQL on {MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}")
    else:
        print("!" * 70)
        print(f"[WARNING] XAMPP MySQL is NOT running on {MYSQL_HOST}:{MYSQL_PORT}!")
        print("Please open XAMPP Control Panel and click 'Start' next to MySQL.")
        print("Falling back to local SQLite temporarily so the server can run.")
        print("!" * 70)
        db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cloudvault_central.db")
        DATABASE_URL = f"sqlite:///{db_path}"

elif not DATABASE_URL:
    db_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cloudvault_central.db")
    DATABASE_URL = f"sqlite:///{db_path}"

# Connection configuration
connect_args = {}
engine_kwargs = {
    "pool_pre_ping": True,
}

if DATABASE_URL.startswith("sqlite"):
    connect_args = {"check_same_thread": False}
    engine_kwargs["connect_args"] = connect_args
elif "mysql" in DATABASE_URL:
    engine_kwargs["pool_recycle"] = 3600
    engine_kwargs["pool_size"] = 10
    engine_kwargs["max_overflow"] = 20

engine = create_engine(
    DATABASE_URL,
    **engine_kwargs
)

db_session = scoped_session(
    sessionmaker(autocommit=False, autoflush=False, bind=engine)
)

Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    import backend.models
    # Auto-create MySQL database if not exists
    if "mysql" in DATABASE_URL:
        try:
            import pymysql
            base_conn = pymysql.connect(
                host=MYSQL_HOST,
                user=MYSQL_USER,
                password=MYSQL_PASSWORD,
                port=int(MYSQL_PORT)
            )
            c = base_conn.cursor()
            c.execute(f"CREATE DATABASE IF NOT EXISTS `{MYSQL_DB}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
            base_conn.commit()
            base_conn.close()
        except Exception as e:
            logger.warning(f"Could not auto-create MySQL database: {e}")

    try:
        Base.metadata.create_all(bind=engine)
        # Auto-sync any newly added columns from models across Git branches
        from sqlalchemy import inspect
        inspector = inspect(engine)
        with engine.begin() as conn:
            for table_name, table in Base.metadata.tables.items():
                if inspector.has_table(table_name):
                    existing_cols = {col['name'] for col in inspector.get_columns(table_name)}
                    for col in table.columns:
                        if col.name not in existing_cols:
                            col_type = col.type.compile(engine.dialect)
                            nullable = "NULL" if col.nullable else "NOT NULL"
                            default_clause = ""
                            if col.default is not None and not callable(col.default.arg):
                                default_clause = f"DEFAULT '{col.default.arg}'" if isinstance(col.default.arg, str) else f"DEFAULT {col.default.arg}"
                            quote = "`" if "mysql" in DATABASE_URL else '"'
                            alter_sql = f"ALTER TABLE {quote}{table_name}{quote} ADD COLUMN {quote}{col.name}{quote} {col_type} {nullable} {default_clause}".strip()
                            try:
                                conn.execute(text(alter_sql))
                                print(f"[DB AUTO-SYNC] Added column {col.name} to {table_name}")
                            except Exception as col_err:
                                logger.warning(f"Failed to auto-sync column {col.name}: {col_err}")
    except Exception as e:
        logger.error(f"Error initializing DB schema: {e}")
