#!/usr/bin/env python3
"""
Emergency admin 2FA reset script.

Run this directly on the server / inside the Docker container when
you are locked out of the admin panel because your authenticator app
is no longer working:

    python reset-admin-2fa.py

It wipes the TOTP secret from the database with no login required.
After running, you can log into the admin panel with your username
and password only (no 2FA code needed).
"""

import sqlite3
import os
import sys

DB_PATH = os.path.join(os.path.dirname(__file__), "storage", "sqlite.db")

def main():
    if not os.path.exists(DB_PATH):
        print(f"ERROR: Database not found at {DB_PATH}")
        sys.exit(1)

    print(f"Connecting to: {DB_PATH}")
    with sqlite3.connect(DB_PATH) as conn:
        conn.row_factory = sqlite3.Row

        profile = conn.execute("SELECT id, username, totp_enabled FROM admin_profiles LIMIT 1").fetchone()
        if not profile:
            print("ERROR: No admin profile found in the database.")
            sys.exit(1)

        print(f"\nMain admin: {profile['username']}")
        print(f"2FA currently enabled: {'Yes' if profile['totp_enabled'] else 'No'}")

        if not profile['totp_enabled']:
            print("\n2FA is already disabled. Nothing to do.")
            return

        confirm = input("\nReset 2FA for this admin? [yes/no]: ").strip().lower()
        if confirm != "yes":
            print("Aborted.")
            sys.exit(0)

        conn.execute(
            "UPDATE admin_profiles SET totp_secret='', totp_enabled=0, updated_at=datetime('now') WHERE id=?",
            (profile['id'],)
        )
        conn.commit()
        print("\nDone. 2FA has been cleared for the main admin.")
        print("You can now log in with your username and password only.")

    # Also offer to reset a sub-admin's 2FA if needed
    print("\n--- Sub-Admin 2FA Reset ---")
    with sqlite3.connect(DB_PATH) as conn:
        conn.row_factory = sqlite3.Row
        sub_admins = conn.execute(
            "SELECT id, username, totp_enabled FROM admin_accounts WHERE totp_enabled=1 ORDER BY id"
        ).fetchall()

    if not sub_admins:
        print("No sub-admins with 2FA enabled.")
        return

    print("Sub-admins with 2FA enabled:")
    for sa in sub_admins:
        print(f"  [{sa['id']}] {sa['username']}")

    choice = input("\nEnter sub-admin ID to reset their 2FA (or press Enter to skip): ").strip()
    if not choice:
        return
    try:
        sa_id = int(choice)
    except ValueError:
        print("Invalid ID. Skipping.")
        return

    with sqlite3.connect(DB_PATH) as conn:
        row = conn.execute("SELECT username FROM admin_accounts WHERE id=?", (sa_id,)).fetchone()
        if not row:
            print(f"Sub-admin ID {sa_id} not found.")
            return
        confirm2 = input(f"Reset 2FA for sub-admin '{row['username']}'? [yes/no]: ").strip().lower()
        if confirm2 != "yes":
            print("Skipped.")
            return
        conn.execute(
            "UPDATE admin_accounts SET totp_secret='', totp_enabled=0 WHERE id=?",
            (sa_id,)
        )
        conn.commit()
        print(f"Done. 2FA cleared for sub-admin '{row['username']}'.")


if __name__ == "__main__":
    main()
