"""
BizNode Backup Runner
Run manually or via Windows Task Scheduler.

Usage:
  python backup/run_backup.py              # Full backup (PG + Qdrant + GDrive)
  python backup/run_backup.py --local      # Local backup only (no GDrive upload)
  python backup/run_backup.py --check      # Check if backup is due and run if needed
  python backup/run_backup.py --schedule   # Install Windows Task Scheduler task
"""

import sys
import logging
import argparse
from pathlib import Path
from datetime import datetime, timezone, timedelta

# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(PROJECT_ROOT))

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler(PROJECT_ROOT / "logs" / "backup.log", mode="a"),
    ],
)
logger = logging.getLogger("biznode.backup")


def check_and_run():
    """Check if a backup is overdue and run if needed (catch-up logic)."""
    from backup.backup_engine import get_last_backup_time, run_backup

    last = get_last_backup_time()
    now = datetime.now(timezone.utc)

    if last is None:
        logger.info("No previous backup found. Running first backup...")
        return run_backup(upload_to_gdrive=True)

    hours_since = (now - last).total_seconds() / 3600

    if hours_since >= 20:  # ~20 hours = catch missed daily backup
        logger.info(f"Last backup was {hours_since:.1f} hours ago. Running catch-up backup...")
        return run_backup(upload_to_gdrive=True)
    else:
        logger.info(f"Last backup was {hours_since:.1f} hours ago. No backup needed yet.")
        return True, [], None


def install_schedule():
    """Install a Windows Task Scheduler task for daily 5 PM backup."""
    import subprocess

    python_exe = sys.executable
    script_path = str(Path(__file__).resolve())

    task_name = "BizNodeDailyBackup"

    # Build schtasks command for daily at 17:00
    # /SC DAILY = daily schedule
    # /ST 17:00 = start time 5:00 PM
    # /RI 1440  = repeat interval (catch-up: re-run next day if missed)
    cmd = [
        "schtasks", "/Create",
        "/TN", task_name,
        "/TR", f'"{python_exe}" "{script_path}" --check',
        "/SC", "DAILY",
        "/ST", "17:00",
        "/F",  # Force overwrite if exists
    ]

    logger.info(f"Creating scheduled task: {task_name}")
    logger.info(f"Command: {' '.join(cmd)}")

    result = subprocess.run(cmd, capture_output=True, text=True)

    if result.returncode == 0:
        logger.info(f"Task '{task_name}' created successfully!")
        logger.info("Backup will run daily at 5:00 PM")
        logger.info("If missed, it will catch up on next run")

        # Also enable "run as soon as possible after a scheduled start is missed"
        xml_cmd = [
            "schtasks", "/Change",
            "/TN", task_name,
            "/ENABLE",
        ]
        subprocess.run(xml_cmd, capture_output=True, text=True)

        print(f"\nScheduled task '{task_name}' installed!")
        print("  Schedule: Daily at 5:00 PM")
        print("  Catch-up: Will run on next login if missed")
        print(f"  Command:  {python_exe} {script_path} --check")
        print(f"\nManage with: schtasks /Query /TN {task_name}")
        print(f"Delete with: schtasks /Delete /TN {task_name} /F")
    else:
        logger.error(f"Failed to create task: {result.stderr}")
        print(f"Error: {result.stderr}")
        print("Try running as Administrator if you get access denied.")
    return result.returncode == 0


def main():
    parser = argparse.ArgumentParser(description="BizNode Backup Runner")
    parser.add_argument("--local", action="store_true", help="Local backup only, no Google Drive upload")
    parser.add_argument("--check", action="store_true", help="Check if backup is due and run if needed")
    parser.add_argument("--schedule", action="store_true", help="Install Windows Task Scheduler task (daily 5 PM)")
    args = parser.parse_args()

    # Ensure logs dir exists
    (PROJECT_ROOT / "logs").mkdir(exist_ok=True)

    if args.schedule:
        install_schedule()
        return

    if args.check:
        success, files, error = check_and_run()
    else:
        from backup.backup_engine import run_backup
        success, files, error = run_backup(upload_to_gdrive=not args.local)

    print("\n" + "=" * 60)
    if success:
        print(f"BACKUP COMPLETE - {len(files)} files")
        for f in files:
            print(f"  {f}")
    else:
        print(f"BACKUP COMPLETED WITH ERRORS")
        if error:
            print(f"  Errors: {error}")
        if files:
            print(f"  Files created: {len(files)}")
            for f in files:
                print(f"    {f}")
    print("=" * 60)


if __name__ == "__main__":
    main()
