#!/usr/bin/env python3
"""Create a new user for the Venture Fund CRM."""

import sys
import os
import getpass

# Add parent directory to path
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'backend'))
from server import get_db, hash_password, generate_id, init_db

def main():
    init_db()

    print("\n  Create New CRM User")
    print("  " + "=" * 30 + "\n")

    username = input("  Username: ").strip()
    if not username:
        print("  Error: Username required")
        sys.exit(1)

    email = input("  Email: ").strip()
    if not email:
        print("  Error: Email required")
        sys.exit(1)

    full_name = input("  Full Name: ").strip()
    if not full_name:
        print("  Error: Full name required")
        sys.exit(1)

    password = getpass.getpass("  Password: ")
    if len(password) < 6:
        print("  Error: Password must be at least 6 characters")
        sys.exit(1)

    confirm = getpass.getpass("  Confirm Password: ")
    if password != confirm:
        print("  Error: Passwords don't match")
        sys.exit(1)

    role = input("  Role (admin/manager/member) [member]: ").strip() or "member"
    if role not in ['admin', 'manager', 'member']:
        print("  Error: Invalid role")
        sys.exit(1)

    conn = get_db()

    # Check for existing
    existing = conn.execute("SELECT id FROM users WHERE username = ? OR email = ?",
                            (username, email)).fetchone()
    if existing:
        print(f"\n  Error: User with that username or email already exists")
        conn.close()
        sys.exit(1)

    user_id = generate_id()
    conn.execute("""
        INSERT INTO users (id, username, email, password_hash, full_name, role)
        VALUES (?, ?, ?, ?, ?, ?)
    """, (user_id, username, email, hash_password(password), full_name, role))
    conn.commit()
    conn.close()

    print(f"\n  User '{username}' created successfully!")
    print(f"  Role: {role}")
    print(f"  ID: {user_id}\n")

if __name__ == "__main__":
    main()
