#!/usr/bin/env python3
"""
Teszt szkript a hierarchikus System Parameters működésének ellenőrzéséhez.
Futtatás: docker exec sf_api python /app/test_hierarchical_params.py
"""
import asyncio
import sys
import os
sys.path.insert(0, '/app')

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.models.system import SystemParameter, ParameterScope
from app.services.system_service import system_service

DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+asyncpg://postgres:postgres@postgres:5432/service_finder")

async def test_hierarchical():
    engine = create_async_engine(DATABASE_URL, echo=False)
    async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
    
    async with async_session() as db:
        # Töröljük a teszt paramétereket, ha vannak
        await db.execute(
            SystemParameter.__table__.delete().where(SystemParameter.key == "test.hierarchical")
        )
        await db.commit()
        
        # 1. GLOBAL paraméter létrehozása
        global_param = SystemParameter(
            key="test.hierarchical",
            value={"message": "global value"},
            scope_level=ParameterScope.GLOBAL,
            scope_id=None,
            category="test",
            is_active=True,
        )
        db.add(global_param)
        
        # 2. COUNTRY paraméter létrehozása (HU)
        country_param = SystemParameter(
            key="test.hierarchical",
            value={"message": "country HU value"},
            scope_level=ParameterScope.COUNTRY,
            scope_id="HU",
            category="test",
            is_active=True,
        )
        db.add(country_param)
        
        # 3. REGION paraméter létrehozása (budapest)
        region_param = SystemParameter(
            key="test.hierarchical",
            value={"message": "region budapest value"},
            scope_level=ParameterScope.REGION,
            scope_id="budapest",
            category="test",
            is_active=True,
        )
        db.add(region_param)
        
        # 4. USER paraméter létrehozása (user_123)
        user_param = SystemParameter(
            key="test.hierarchical",
            value={"message": "user user_123 value"},
            scope_level=ParameterScope.USER,
            scope_id="user_123",
            category="test",
            is_active=True,
        )
        db.add(user_param)
        
        await db.commit()
        
        # Teszt: csak global scope (nincs user, region, country)
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", default=None)
        print(f"Global only: {value}")
        assert value["message"] == "global value"
        
        # COUNTRY scope (HU)
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", country_code="HU", default=None)
        print(f"Country HU: {value}")
        assert value["message"] == "country HU value"
        
        # REGION scope (budapest) – a region a country feletti prioritás? A prioritási sorrend: User > Region > Country > Global
        # Ha region_id megadva, de country_code is, akkor region elsőbbséget élvez.
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", region_id="budapest", country_code="HU", default=None)
        print(f"Region budapest (with country HU): {value}")
        assert value["message"] == "region budapest value"
        
        # USER scope (user_123) – legmagasabb prioritás
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", user_id="user_123", region_id="budapest", country_code="HU", default=None)
        print(f"User user_123 (with region and country): {value}")
        assert value["message"] == "user user_123 value"
        
        # Nem létező user, de létező region
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", user_id="nonexistent", region_id="budapest", country_code="HU", default=None)
        print(f"Non-existent user, region budapest: {value}")
        assert value["message"] == "region budapest value"
        
        # Nem létező region, de létező country
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", region_id="nonexistent", country_code="HU", default=None)
        print(f"Non-existent region, country HU: {value}")
        assert value["message"] == "country HU value"
        
        # Semmi specifikus – global
        value = await system_service.get_scoped_parameter(db, "test.hierarchical", default=None)
        print(f"Fallback to global: {value}")
        assert value["message"] == "global value"
        
        # Törlés
        await db.execute(
            SystemParameter.__table__.delete().where(SystemParameter.key == "test.hierarchical")
        )
        await db.commit()
        print("✅ Minden teszt sikeres!")
        
if __name__ == "__main__":
    asyncio.run(test_hierarchical())