from __future__ import annotations

import os
import shutil
import subprocess
import sys
from datetime import datetime
from pathlib import Path

from config import BASE_DIR, DATA_DIR

from app.excel_import.config import BACKUPS_DIR, PROD_DB_PATH, TEST_DB_PATH


def db_uri(path: Path) -> str:
    return f"sqlite:///{path.resolve()}"


def backup_database(source: Path, label: str = "copropriete") -> Path:
    BACKUPS_DIR.mkdir(parents=True, exist_ok=True)
    ts = datetime.now().strftime("%Y-%m-%d_%H%M%S")
    dest = BACKUPS_DIR / f"{label}-{ts}.db"
    if not source.is_file():
        raise FileNotFoundError(f"Base introuvable : {source}")
    shutil.copy2(source, dest)
    return dest


def initialize_database(db_path: Path) -> None:
    if db_path.exists():
        db_path.unlink()
    env = os.environ.copy()
    env["DATABASE_URL"] = db_uri(db_path)
    subprocess.run(
        [sys.executable, str(BASE_DIR / "init_db.py")],
        cwd=str(BASE_DIR),
        env=env,
        check=True,
    )


def prepare_target_database(*, prod: bool, reset: bool) -> Path:
    target = PROD_DB_PATH if prod else TEST_DB_PATH
    if prod:
        if reset:
            backup_database(PROD_DB_PATH)
            initialize_database(target)
    elif reset:
        initialize_database(target)
    elif not target.is_file():
        initialize_database(target)
    return target


def create_app_for_db(db_path: Path):
    os.environ["DATABASE_URL"] = db_uri(db_path)
    from app import create_app

    return create_app()
