from __future__ import annotations

import argparse
import getpass
from pathlib import Path
import secrets
import string
import sys


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from sqlalchemy import select, update

from app.database import SessionLocal, init_database
from app.models import User, UserSession
from app.security import ensure_user_account_uid, hash_password, normalize_email
from app.time_utils import utc_now_naive


def _generated_password(length: int = 28) -> str:
    alphabet = string.ascii_letters + string.digits + "!@#$%*-_=+"
    required = [
        secrets.choice(string.ascii_lowercase),
        secrets.choice(string.ascii_uppercase),
        secrets.choice(string.digits),
        secrets.choice("!@#$%*-_=+"),
    ]
    required.extend(secrets.choice(alphabet) for _ in range(length - len(required)))
    secrets.SystemRandom().shuffle(required)
    return "".join(required)


def _arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Cria ou promove uma conta administrativa persistente do FSE3D.",
    )
    parser.add_argument("--email", required=True)
    parser.add_argument("--name", default="Administrador FSE3D")
    password_mode = parser.add_mutually_exclusive_group()
    password_mode.add_argument("--generate-password", action="store_true")
    password_mode.add_argument("--password-stdin", action="store_true")
    parser.add_argument(
        "--keep-sessions",
        action="store_true",
        help="Preserva sessoes existentes ao promover ou trocar a senha.",
    )
    return parser.parse_args()


def main() -> int:
    args = _arguments()
    email = normalize_email(args.email)
    password: str | None = None
    if args.generate_password:
        password = _generated_password()
    elif args.password_stdin:
        password = getpass.getpass("")

    init_database()
    with SessionLocal() as db:
        user = db.execute(select(User).where(User.email == email)).scalar_one_or_none()
        created = user is None
        if user is None:
            if password is None:
                raise SystemExit("Uma conta nova exige --generate-password ou --password-stdin.")
            user = User(
                account_uid=None,
                name=" ".join(args.name.split()),
                email=email,
                password_hash=hash_password(password),
                is_active=True,
                is_admin=True,
            )
            db.add(user)
            db.commit()
            db.refresh(user)
        else:
            user.name = " ".join(args.name.split()) or user.name
            user.is_active = True
            user.is_admin = True
            if password is not None:
                user.password_hash = hash_password(password)
            db.commit()
            db.refresh(user)

        ensure_user_account_uid(db, user)
        if not args.keep_sessions:
            db.execute(
                update(UserSession)
                .where(UserSession.user_id == user.id, UserSession.revoked_at.is_(None))
                .values(revoked_at=utc_now_naive())
            )
            db.commit()

        print(f"ADMIN_STATUS={'created' if created else 'promoted'}")
        print(f"ADMIN_EMAIL={user.email}")
        print(f"ADMIN_ACCOUNT_UID={user.account_uid}")
        if args.generate_password:
            print(f"ADMIN_PASSWORD={password}")
    return 0


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