"""Safely reset a Shop Manager POS account password without deleting data."""
import getpass
import os
import shutil
import sqlite3
from datetime import datetime

from werkzeug.security import generate_password_hash


def database_path():
    data_dir = os.environ.get("POS_DATA_DIR")
    if not data_dir:
        data_dir = os.path.join(os.environ.get("LOCALAPPDATA", ""), "ShopManagerPOS")
    installed_db = os.path.join(data_dir, "shop.db")
    source_db = os.path.join(os.path.dirname(__file__), "shop.db")
    return installed_db if os.path.exists(installed_db) else source_db


def main():
    db_path = database_path()
    if not os.path.exists(db_path):
        raise SystemExit(f"Database was not found: {db_path}")

    username = input("Username [admin]: ").strip() or "admin"
    new_password = getpass.getpass("New password (minimum 6 characters): ")
    confirm_password = getpass.getpass("Confirm new password: ")
    if len(new_password) < 6:
        raise SystemExit("Password must be at least 6 characters.")
    if new_password != confirm_password:
        raise SystemExit("Passwords do not match. Nothing was changed.")

    backup_path = f"{db_path}.before-password-reset-{datetime.now():%Y%m%d-%H%M%S}.bak"
    shutil.copy2(db_path, backup_path)

    with sqlite3.connect(db_path) as connection:
        columns = {row[1] for row in connection.execute("PRAGMA table_info(user)")}
        updates = ["password_hash = ?"]
        values = [generate_password_hash(new_password)]
        if "must_change_password" in columns:
            updates.append("must_change_password = 0")
        if "reset_code_hash" in columns:
            updates.append("reset_code_hash = NULL")
        if "reset_code_expires" in columns:
            updates.append("reset_code_expires = NULL")
        values.append(username)
        result = connection.execute(
            f"UPDATE user SET {', '.join(updates)} WHERE username = ?", values
        )
        if result.rowcount != 1:
            raise SystemExit(f"Account '{username}' was not found. Database backup kept at: {backup_path}")

    print("Password reset successful.")
    print(f"Database backup created: {backup_path}")
    print("Start Shop Manager POS and sign in with the new password.")


if __name__ == "__main__":
    main()
