#!/usr/bin/env python3
"""Crea un respaldo local para SQLite o MySQL/MariaDB en cPanel."""

import gzip
import os
import shutil
import sqlite3
import subprocess
import sys
import tempfile
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
os.chdir(ROOT)

from app.config import settings  # noqa: E402

BACKUP_DIR = ROOT / "backups"
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")

if settings.database_url.startswith("sqlite"):
    source = Path(settings.database_url.replace("sqlite:///", "", 1))
    destination = BACKUP_DIR / f"alberto-smith-sqlite-{stamp}.db"
    with sqlite3.connect(source) as src, sqlite3.connect(destination) as dst:
        src.backup(dst)
    print(destination)
    raise SystemExit(0)

if settings.database_url.startswith("mysql"):
    host = os.getenv("MYSQL_HOST", "localhost")
    port = os.getenv("MYSQL_PORT", "3306")
    database = os.environ["MYSQL_DATABASE"]
    username = os.environ["MYSQL_USER"]
    password = os.environ["MYSQL_PASSWORD"]
    destination = BACKUP_DIR / f"alberto-smith-mysql-{stamp}.sql.gz"

    with tempfile.NamedTemporaryFile("w", delete=False) as credentials:
        credentials.write("[client]\n")
        credentials.write(f"host={host}\nport={port}\nuser={username}\npassword={password}\n")
        credentials_path = credentials.name
    os.chmod(credentials_path, 0o600)
    try:
        command = [
            "mysqldump",
            f"--defaults-extra-file={credentials_path}",
            "--single-transaction",
            "--routines",
            "--triggers",
            "--default-character-set=utf8mb4",
            database,
        ]
        with gzip.open(destination, "wb") as output:
            subprocess.run(command, stdout=output, check=True)
    finally:
        Path(credentials_path).unlink(missing_ok=True)
    print(destination)
    raise SystemExit(0)

raise SystemExit("El respaldo automático de cPanel admite SQLite o MySQL/MariaDB.")
