"""Deployment Script: Full Synchronization to Production Cloud VM.

Performs:
1. One-time recursive push of `app/`, `db/migrations/`, `scripts/`, `Dockerfile`, `docker-compose.prod.yml`, `pyproject.toml`
2. Applies pending migrations (0023, 0024) inside the postgres container
3. Verifies container health and Uvicorn hot-reload
"""

from __future__ import annotations

import os
from pathlib import Path
import subprocess
import sys
import time

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
    sys.stderr.reconfigure(encoding="utf-8", errors="replace")

LOCAL_ROOT = Path(__file__).resolve().parent.parent
REMOTE_HOST = "dscons"
REMOTE_ROOT = "/opt/dscons"
SSH_KEY = Path.home() / ".ssh" / "google_compute_engine"

def run_ssh(cmd: str) -> subprocess.CompletedProcess:
    ssh_cmd = [
        "ssh",
        "-i", str(SSH_KEY),
        "-o", "StrictHostKeyChecking=accept-new",
        REMOTE_HOST,
        cmd,
    ]
    return subprocess.run(ssh_cmd, capture_output=True, text=True)

def run_scp(local_src: str, remote_dest: str, recursive: bool = True) -> bool:
    scp_cmd = [
        "scp",
        "-i", str(SSH_KEY),
        "-o", "StrictHostKeyChecking=accept-new",
    ]
    if recursive:
        scp_cmd.append("-r")
    scp_cmd.extend([local_src, f"{REMOTE_HOST}:{remote_dest}"])

    print(f"  -> SCP: {local_src} -> {remote_dest}...")
    res = subprocess.run(scp_cmd, capture_output=True, text=True, cwd=str(LOCAL_ROOT))
    if res.returncode == 0:
        print(f"     [OK] Đồng bộ thành công.")
        return True
    else:
        print(f"     [FAILED] Lỗi: {res.stderr.strip()}")
        return False

def main() -> int:
    print("=" * 65)
    print("  DSCons Enterprise Production Deployment & Live Sync")
    print(f"  Local Root : {LOCAL_ROOT}")
    print(f"  Remote Host: {REMOTE_HOST} ({REMOTE_ROOT})")
    print("=" * 65)

    # 1. Test SSH Connection
    print("\n[Bước 1/5] Kiểm tra kết nối SSH...")
    res = run_ssh("echo CONNECTED && hostname")
    if res.returncode != 0 or "CONNECTED" not in res.stdout:
        print(f"[ERROR] Không thể kết nối SSH tới {REMOTE_HOST}: {res.stderr}")
        return 1
    print(f"  [OK] Đã kết nối thành công tới: {res.stdout.strip().splitlines()[-1]}")

    # 2. Push source directories
    print("\n[Bước 2/5] Đẩy mã nguồn và tệp cấu hình lên Cloud VM...")
    dirs_to_sync = [
        ("app", f"{REMOTE_ROOT}/"),
        ("db/migrations", f"{REMOTE_ROOT}/db/"),
        ("scripts", f"{REMOTE_ROOT}/"),
    ]
    for src, dst in dirs_to_sync:
        if not run_scp(src, dst, recursive=True):
            return 1

    files_to_sync = [
        ("Dockerfile", f"{REMOTE_ROOT}/Dockerfile"),
        ("docker-compose.prod.yml", f"{REMOTE_ROOT}/docker-compose.prod.yml"),
        ("pyproject.toml", f"{REMOTE_ROOT}/pyproject.toml"),
    ]
    for src, dst in files_to_sync:
        if not run_scp(src, dst, recursive=False):
            return 1

    # 3. Apply Migrations to Remote PostgreSQL
    print("\n[Bước 3/5] Thực thi database migrations 0023 và 0024 vào PostgreSQL...")
    migration_cmds = [
        f"sudo docker exec -i dscons-postgres psql -U dscons_user -d dscons_operations < {REMOTE_ROOT}/db/migrations/0023_smart_debt_clearing_ledger.sql",
        f"sudo docker exec -i dscons-postgres psql -U dscons_user -d dscons_operations < {REMOTE_ROOT}/db/migrations/0024_warehouse_dispatch_and_material_wastage.sql",
    ]
    for m_cmd in migration_cmds:
        print(f"  -> Thực thi: {m_cmd.split('<')[-1].strip()}")
        m_res = run_ssh(m_cmd)
        if m_res.returncode == 0:
            print(f"     [OK] Migration thành công.")
        else:
            print(f"     [NOTICE] {m_res.stderr.strip() or m_res.stdout.strip()}")

    # 4. Verify DB schema migrations
    print("\n[Bước 4/5] Xác minh danh sách migrations đã áp dụng...")
    chk_res = run_ssh("sudo docker exec dscons-postgres psql -U dscons_user -d dscons_operations -c 'SELECT version, installed_on FROM schema_migrations ORDER BY version DESC LIMIT 5;'")
    print(chk_res.stdout)

    # 5. Check backend health & uvicorn logs
    print("\n[Bước 5/5] Kiểm tra Uvicorn Hot-Reload và Healthcheck...")
    time.sleep(2)
    health_res = run_ssh("sudo docker exec dscons-backend curl -s http://127.0.0.1:8000/health")
    print(f"  Healthcheck response: {health_res.stdout.strip()}")

    log_res = run_ssh("sudo docker logs --tail 15 dscons-backend")
    print("\n  Uvicorn Container Logs (Recent):")
    print("  " + "\n  ".join(log_res.stdout.strip().splitlines()[-10:]))

    print("\n" + "=" * 65)
    print("  [HOÀN TẤT] Đồng bộ mã nguồn và cập nhật hệ thống thành công!")
    print("=" * 65)
    return 0

if __name__ == "__main__":
    sys.exit(main())
