import sqlite3
import os
from datetime import datetime
from pathlib import Path

from modules.core import storage_paths


def _int_env(name, default):
    raw_value = os.getenv(name)
    if raw_value is None:
        return default
    try:
        return int(raw_value)
    except ValueError:
        return default


def _cleanup_idb_backups(backup_dir: Path, keep_last: int):
    if keep_last < 1:
        keep_last = 1

    backups = sorted(
        backup_dir.glob("IDB_*.db"),
        key=lambda p: p.stat().st_mtime,
        reverse=True,
    )

    for old_backup in backups[keep_last:]:
        try:
            old_backup.unlink()
        except OSError:
            continue


def connection(db_target=None):
    """
    Tworzy połączenie z wybraną bazą danych.
    - Jeśli db_target == 'agents', używa nowej bazy w instances/agents.db
    - W przeciwnym razie używa domyślnej bazy instances/IDB.db
    """
    db_path = storage_paths.agents_db_path() if db_target == "agents" else storage_paths.idb_db_path()
    return sqlite3.connect(db_path)


def backup_idb_database():
    """
    Tworzy timestampowany backup tylko bazy instances/IDB.db
    do instances/backup.

    Uses SQLite's native Connection.backup() so the backup is a
    transactionally consistent snapshot of committed data (including any
    WAL-resident state), not a filesystem copy of the live main file. The
    snapshot is written to a temporary sibling, verified with
    PRAGMA quick_check, then atomically renamed to the final IDB_*.db name --
    so a partial/failed backup is never published under that name.

    Zwraca ścieżkę do backupu (str) lub None, jeśli plik źródłowy nie istnieje.
    Backup creation errors propagate; the caller (trigger_idb_backup) owns the
    log-and-continue behaviour.
    """
    source = storage_paths.idb_db_path()
    if not source.exists():
        return None

    backup_dir = storage_paths.instances_backup_dir()
    backup_dir.mkdir(parents=True, exist_ok=True)

    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
    backup_path = backup_dir / f"IDB_{timestamp}.db"
    # Temp name that does NOT match the IDB_*.db retention glob.
    tmp_path = backup_dir / f"IDB_{timestamp}.db.tmp"

    try:
        # sqlite3's context manager only commits on exit, it does not close;
        # both connections must be closed before os.replace() or Windows
        # rejects the rename (file in use). Manage the lifecycle explicitly.
        src = sqlite3.connect(source)
        try:
            dst = sqlite3.connect(tmp_path)
            try:
                src.backup(dst)
                if dst.execute("PRAGMA quick_check").fetchone()[0] != "ok":
                    raise sqlite3.DatabaseError("IDB backup failed quick_check")
            finally:
                dst.close()
        finally:
            src.close()
        os.replace(tmp_path, backup_path)
    except BaseException:
        try:
            if tmp_path.exists():
                tmp_path.unlink()
        except OSError:
            pass
        raise

    _cleanup_idb_backups(
        backup_dir,
        keep_last=_int_env("IDB_BACKUP_KEEP_LAST", 60),
    )
    return str(backup_path)
