#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Seed Demo Users
Creates demo user accounts for production demo environment
"""

import asyncio
import sys
from pathlib import Path

project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

import os
os.environ.setdefault("AUTH_DATABASE_URL", os.getenv("AUTH_DATABASE_URL"))

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy import select
import structlog
import uuid
import json

logger = structlog.get_logger()

# Demo user configurations (public credentials for prospects)
DEMO_USERS = [
    {
        "id": "c1a2b3c4-d5e6-47a8-b9c0-d1e2f3a4b5c6",
        "email": "demo.individual@panaderiasanpablo.com",
        "password_hash": "$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewY5GyYVPWzO8hGi",  # DemoSanPablo2024!
        "full_name": "María García López",
        "phone": "+34 912 345 678",
        "language": "es",
        "timezone": "Europe/Madrid",
        "role": "owner",
        "is_active": True,
        "is_verified": True,
        "is_demo": True
    },
    {
        "id": "d2e3f4a5-b6c7-48d9-e0f1-a2b3c4d5e6f7",
        "email": "demo.central@panaderialaespiga.com",
        "password_hash": "$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewY5GyYVPWzO8hGi",  # DemoLaEspiga2024!
        "full_name": "Carlos Martínez Ruiz",
        "phone": "+34 913 456 789",
        "language": "es",
        "timezone": "Europe/Madrid",
        "role": "owner",
        "is_active": True,
        "is_verified": True,
        "is_demo": True
    }
]


def load_staff_users():
    """Load staff users from JSON file"""
    json_file = Path(__file__).parent / "usuarios_staff_es.json"
    if not json_file.exists():
        logger.warning(f"Staff users JSON not found: {json_file}, skipping staff users")
        return []

    with open(json_file, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # Combine both individual and central bakery staff
    all_staff = data.get("staff_individual_bakery", []) + data.get("staff_central_bakery", [])
    logger.info(f"Loaded {len(all_staff)} staff users from JSON")
    return all_staff


async def seed_demo_users():
    """Seed demo users into auth database"""

    database_url = os.getenv("AUTH_DATABASE_URL")
    if not database_url:
        logger.error("AUTH_DATABASE_URL environment variable not set")
        return False

    logger.info("Connecting to auth database", url=database_url.split("@")[-1])

    engine = create_async_engine(database_url, echo=False)
    session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

    try:
        async with session_factory() as session:
            # Import User model
            try:
                from app.models.users import User
            except ImportError:
                from services.auth.app.models.users import User
            from datetime import datetime, timezone

            # Load staff users from JSON
            staff_users = load_staff_users()

            # Combine owner users with staff users
            all_users = DEMO_USERS + staff_users
            logger.info(f"Seeding {len(all_users)} total users ({len(DEMO_USERS)} owners + {len(staff_users)} staff)")

            created_count = 0
            skipped_count = 0

            for user_data in all_users:
                # Check if user already exists
                result = await session.execute(
                    select(User).where(User.email == user_data["email"])
                )
                existing_user = result.scalar_one_or_none()

                if existing_user:
                    logger.debug(f"Demo user already exists: {user_data['email']}")
                    skipped_count += 1
                    continue

                # Create new demo user
                user = User(
                    id=uuid.UUID(user_data["id"]),
                    email=user_data["email"],
                    hashed_password=user_data["password_hash"],
                    full_name=user_data["full_name"],
                    phone=user_data.get("phone"),
                    language=user_data.get("language", "es"),
                    timezone=user_data.get("timezone", "Europe/Madrid"),
                    role=user_data.get("role", "owner"),
                    is_active=user_data.get("is_active", True),
                    is_verified=user_data.get("is_verified", True),
                    created_at=datetime.now(timezone.utc),
                    updated_at=datetime.now(timezone.utc)
                )

                session.add(user)
                created_count += 1
                logger.debug(f"Created demo user: {user_data['email']} ({user_data.get('role', 'owner')})")

            await session.commit()
            logger.info(f"Demo users seeded successfully: {created_count} created, {skipped_count} skipped")
            return True

    except Exception as e:
        logger.error(f"Failed to seed demo users: {str(e)}")
        return False

    finally:
        await engine.dispose()


if __name__ == "__main__":
    result = asyncio.run(seed_demo_users())
    sys.exit(0 if result else 1)
