# /opt/docker/dev/service_finder/backend/app/tests_internal/seeds/seed_system.py
import asyncio
import logging
import uuid
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.models.identity import User, Person, UserRole
from app.models.system import SystemParameter
# JAVÍTOTT IMPORTOK: A grep alapján szétválasztva
from app.models import PointRule, LevelConfig, UserStats
from app.models.core_logic import SubscriptionTier
from app.core.security import get_password_hash
from app.core.config import settings

logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] Sentinel-Seed: %(message)s')
logger = logging.getLogger("System-Seeder")

async def seed_data():
    """ Rendszer alapadatok inicializálása a megfelelő modellekből. """
    async with AsyncSessionLocal() as db:
        logger.info("🚀 Rendszer-alapozás indítása (MB2.0 Standard)...")

        admin_email = settings.INITIAL_ADMIN_EMAIL
        admin_password = settings.INITIAL_ADMIN_PASSWORD

        if not admin_email or not admin_password:
            logger.error("❌ HIBA: Admin hitelesítési adatok hiányoznak!")
            return

        # 1. Superadmin és Person kapcsolat
        stmt = select(User).where(User.email == admin_email)
        admin_exists = (await db.execute(stmt)).scalar_one_or_none()

        if not admin_exists:
            new_person = Person(
                first_name="Rendszer",
                last_name="Adminisztrátor",
                id_uuid=uuid.uuid4(),
                is_active=True
            )
            db.add(new_person)
            await db.flush()

            new_admin = User(
                email=admin_email,
                hashed_password=get_password_hash(admin_password),
                role=UserRole.superadmin,
                is_active=True,
                person_id=new_person.id
            )
            db.add(new_admin)
            await db.flush()
            
            # Statisztikai rekord (Gamification)
            db.add(UserStats(user_id=new_admin.id, total_xp=0, current_level=1))
            logger.info(f"✅ Superadmin létrehozva: {admin_email}")

        # 2. Rendszerparaméterek (JSONB értékekkel)
        params = [
            ("SECURITY_MAX_RECORDS_PER_HOUR", {"limit": 50}, "Biztonsági limit"),
            ("VEHICLE_LIMIT", {"default": 5}, "Alapértelmezett jármű limit")
        ]
        for key, val, desc in params:
            stmt_p = select(SystemParameter).where(SystemParameter.key == key)
            if not (await db.execute(stmt_p)).scalar_one_or_none():
                db.add(SystemParameter(key=key, value=val, description=desc))

        # 3. Gamification Szabályok (gamification.py-ból)
        rules = [("ASSET_REGISTER", 100), ("ASSET_REVIEW", 75)]
        for key, pts in rules:
            stmt_r = select(PointRule).where(PointRule.action_key == key)
            if not (await db.execute(stmt_r)).scalar_one_or_none():
                db.add(PointRule(action_key=key, points=pts))

        await db.commit()
        logger.info("✨ Rendszer alapadatok rögzítve.")

if __name__ == "__main__":
    asyncio.run(seed_data())