#!/usr/bin/env python3
"""create_admin.py — Creates/updates the panel admin user in the DB.

The password is stored in the DB only as a salted PBKDF2 hash (NOT plaintext).
If no password is provided, a STRONG password is generated and printed once.

Backend uses DATABASE_URL (default SQLite state/coinbot.db; PostgreSQL on the server).
If the DB has at least one user, panel LOGIN becomes mandatory.

Example:
  python scripts/create_admin.py                          # admin + generated strong password
  python scripts/create_admin.py --user admin --password 'kendi-parolam'
  python scripts/create_admin.py --rotate                 # new strong password for the existing admin
"""
from __future__ import annotations

import argparse
import pathlib
import secrets
import string
import sys

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))

from dotenv import load_dotenv

load_dotenv(pathlib.Path(__file__).resolve().parent.parent / ".env")

from rich.console import Console

from coinbot.db import Database
from webapp import auth

console = Console()


def strong_password(n: int = 20) -> str:
    """Readable yet strong password (excluding ambiguous O/0/I/l characters, with symbols)."""
    upper = "ABCDEFGHJKLMNPQRSTUVWXYZ"   # no O,I
    lower = "abcdefghijkmnopqrstuvwxyz"  # no l
    digits = "23456789"                  # no 0,1
    symbols = "!@#$%^&*-_=+?"
    pools = [upper, lower, digits, symbols]
    # Guarantee at least one character from each pool, then fill the rest randomly.
    chars = [secrets.choice(p) for p in pools]
    allc = upper + lower + digits + symbols
    chars += [secrets.choice(allc) for _ in range(max(0, n - len(chars)))]
    # Shuffle (using secrets)
    for i in range(len(chars) - 1, 0, -1):
        j = secrets.randbelow(i + 1)
        chars[i], chars[j] = chars[j], chars[i]
    return "".join(chars)


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(prog="create_admin.py", description="Panel admin kullanıcısı (DB, PBKDF2).")
    p.add_argument("--user", default="admin", help="Kullanıcı adı (varsayılan admin).")
    p.add_argument("--password", default=None, help="Parola (verilmezse güçlü bir parola üretilir).")
    p.add_argument("--rotate", action="store_true", help="Yeni güçlü parola üret (parola vermeden).")
    args = p.parse_args(argv)

    try:
        db = Database()
    except Exception as exc:  # noqa: BLE001
        console.print(f"[bold red]DB acilamadi:[/] {exc}")
        return 1

    pw = args.password or strong_password()
    db.set_user(args.user, auth.hash_password(pw))

    console.print(f"[bold green]✓ Admin kaydedildi[/]  (DB: {db._safe_url()})")
    console.print(f"   kullanıcı : [bold]{args.user}[/]")
    console.print(f"   parola    : [bold yellow]{pw}[/]")
    if not args.password:
        console.print("[dim]Bu parola yalnızca ŞİMDİ gösterildi; DB'de sadece hash tutulur. Güvenli kaydedin.[/]")
    console.print("[dim]Artık panel LOGIN ister (env parolaya gerek yok). Paneli TLS arkasında yayınlayın.[/]")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
