from datetime import datetime, timezone, timedelta
from typing import Optional, Dict, Any
import logging
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, text

from app.models.identity import User, Person, Wallet, UserRole
from app.models.organization import Organization, OrgType
from app.models.vehicle import OrganizationMember
from app.schemas.auth import UserRegister
from app.core.security import get_password_hash
from app.services.email_manager import email_manager

logger = logging.getLogger(__name__)

class AuthService:
    @staticmethod
    async def get_setting(db: AsyncSession, key: str, default: Any = None) -> Any:
        """Kiolvassa a beállítást az adatbázisból (Admin UI kompatibilis)."""
        try:
            stmt = text("SELECT value FROM data.system_settings WHERE key = :key")
            result = await db.execute(stmt, {"key": key})
            val = result.scalar()
            return val if val is not None else default
        except Exception:
            return default

    @staticmethod
    async def register_new_user(db: AsyncSession, user_in: UserRegister, ip_address: str):
        try:
            # 1. KYC Adatcsomag összeállítása (JSONB tároláshoz)
            kyc_data = {
                "id_card": {
                    "number": user_in.id_card_number,
                    "expiry": str(user_in.id_card_expiry) if user_in.id_card_expiry else None
                },
                "driver_license": {
                    "number": user_in.driver_license_number,
                    "expiry": str(user_in.driver_license_expiry) if user_in.driver_license_expiry else None,
                    "categories": user_in.driver_license_categories
                },
                "special_licenses": {
                    "boat": user_in.boat_license_number,
                    "pilot": user_in.pilot_license_number
                }
            }

            # 2. Person létrehozása
            new_person = Person(
                first_name=user_in.first_name,
                last_name=user_in.last_name,
                mothers_name=user_in.mothers_name,
                birth_place=user_in.birth_place,
                birth_date=user_in.birth_date,
                identity_docs=kyc_data
            )
            db.add(new_person)
            await db.flush()

            # 3. User létrehozása
            hashed_pwd = get_password_hash(user_in.password) if user_in.password else None
            new_user = User(
                email=user_in.email,
                hashed_password=hashed_pwd,
                social_provider=user_in.social_provider,
                social_id=user_in.social_id,
                person_id=new_person.id,
                role=UserRole.USER,
                region_code=user_in.region_code,
                is_active=True
            )
            db.add(new_user)
            await db.flush()

            # 4. Wallet inicializálás
            new_wallet = Wallet(user_id=new_user.id, coin_balance=0.00, xp_balance=0)
            db.add(new_wallet)

            # 5. Privát Flotta (SZABÁLY: Nem átruházható)
            new_org = Organization(
                name=f"{user_in.last_name} {user_in.first_name} flottája",
                org_type=OrgType.INDIVIDUAL,
                owner_id=new_user.id,
                is_active=True,
                is_transferable=False
            )
            db.add(new_org)
            await db.flush()

            # 6. Tagság rögzítése
            db.add(OrganizationMember(organization_id=new_org.id, user_id=new_user.id, role="owner"))

            # 7. Audit Log
            audit_stmt = text("""
                INSERT INTO data.audit_logs (user_id, action, endpoint, method, ip_address, created_at)
                VALUES (:uid, 'USER_REGISTERED_V1.3_FULL_KYC', '/api/v1/auth/register', 'POST', :ip, :now)
            """)
            await db.execute(audit_stmt, {
                "uid": new_user.id,
                "ip": ip_address,
                "now": datetime.now(timezone.utc)
            })

            # 8. Jutalmazás (Dinamikus)
            reward_days = await AuthService.get_setting(db, "auth.reward_days", 14)

            # 9. Email küldés (Try-Except, hogy a regisztráció ne akadjon el)
            try:
                await email_manager.send_email(
                    recipient=user_in.email,
                    template_key="registration_welcome",
                    variables={"first_name": user_in.first_name, "reward_days": reward_days},
                    user_id=new_user.id
                )
            except Exception as e:
                logger.warning(f"Email delivery failed: {str(e)}")

            await db.commit()
            return new_user

        except Exception as e:
            await db.rollback()
            logger.error(f"Critical error in register_new_user: {str(e)}")
            raise e

    @staticmethod
    async def check_email_availability(db: AsyncSession, email: str) -> bool:
        query = select(User).where(and_(User.email == email, User.is_deleted == False))
        result = await db.execute(query)
        return result.scalar_one_or_none() is None