"""
Script to seed a test user account from environment variables.
Intended for use in the test/staging deployment pipeline.

Required environment variables:
  SEED_EMAIL        - User email address
  SEED_PASSWORD     - Plain-text password (will be hashed)
  SEED_PIN          - 4-6 digit parent PIN (stored as plain text)
  SEED_FIRST_NAME   - User first name
  SEED_LAST_NAME    - User last name

Usage:
  python scripts/seed_test_user.py
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from db.db import users_db
from models.user import User
from werkzeug.security import generate_password_hash
from tinydb import Query
import uuid


def seed_test_user() -> bool:
    email = os.environ.get('SEED_EMAIL', '').strip().lower()
    password = os.environ.get('SEED_PASSWORD', '').strip()
    pin = os.environ.get('SEED_PIN', '').strip()
    first_name = os.environ.get('SEED_FIRST_NAME', '').strip()
    last_name = os.environ.get('SEED_LAST_NAME', '').strip()

    missing = [name for name, val in [
        ('SEED_EMAIL', email),
        ('SEED_PASSWORD', password),
        ('SEED_PIN', pin),
        ('SEED_FIRST_NAME', first_name),
        ('SEED_LAST_NAME', last_name),
    ] if not val]

    if missing:
        print(f"Error: Missing required environment variables: {', '.join(missing)}")
        return False

    if not (4 <= len(pin) <= 6 and pin.isdigit()):
        print("Error: SEED_PIN must be 4-6 digits")
        return False

    hashed_password = generate_password_hash(password)
    Query_ = Query()
    existing = users_db.get(Query_.email == email)

    if existing:
        users_db.update(
            {'password': hashed_password, 'pin': pin},
            Query_.email == email
        )
        print(f"✓ Test user updated successfully")
        print(f"  Email:      {email}")
        print(f"  Name:       {first_name} {last_name}")
        print(f"  PIN:        {'*' * len(pin)}")
    else:
        user = User(
            id=str(uuid.uuid4()),
            email=email,
            first_name=first_name,
            last_name=last_name,
            password=hashed_password,
            pin=pin,
            verified=True,
            role='user',
        )
        users_db.insert(user.to_dict())
        print(f"✓ Test user created successfully")
        print(f"  Email:      {email}")
        print(f"  Name:       {first_name} {last_name}")
        print(f"  PIN:        {'*' * len(pin)}")

    return True


if __name__ == '__main__':
    print("=== Seed Test User ===\n")
    success = seed_test_user()
    sys.exit(0 if success else 1)
