#!/usr/bin/env python3
"""
Seed script for system.data_completion_weights table.
Populates default weights for vehicle asset completion percentage calculation.
"""
import asyncio
import logging
from sqlalchemy import select
from app.database import AsyncSessionLocal
from app.models.system.system import SystemDataCompletionWeight

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

async def seed_completion_weights():
    """Seed default data completion weights for entity_type='asset'."""
    async with AsyncSessionLocal() as db:
        # Check if weights already exist for entity_type='asset'
        stmt = select(SystemDataCompletionWeight).where(
            SystemDataCompletionWeight.entity_type == "asset"
        )
        result = await db.execute(stmt)
        existing = result.scalars().all()
        
        if existing:
            logger.info(f"Found {len(existing)} existing weights for entity_type='asset'. Skipping seed.")
            return
        
        # Default weights for vehicle assets (total: 100%)
        weights = [
            {
                "entity_type": "asset",
                "field_name": "license_plate",
                "weight_percent": 20,
                "is_mandatory": False,
                "is_active": True,
                "is_read": False,
                "description": "Rendszám - alapvető azonosító"
            },
            {
                "entity_type": "asset",
                "field_name": "make",
                "weight_percent": 15,
                "is_mandatory": False,
                "is_active": True,
                "is_read": False,
                "description": "Gyártó (márka)"
            },
            {
                "entity_type": "asset",
                "field_name": "model",
                "weight_percent": 15,
                "is_mandatory": False,
                "is_active": True,
                "is_read": False,
                "description": "Modell"
            },
            {
                "entity_type": "asset",
                "field_name": "vin",
                "weight_percent": 30,
                "is_mandatory": False,
                "is_active": True,
                "is_read": False,
                "description": "Alvázszám (VIN) - egyedi azonosító"
            },
            {
                "entity_type": "asset",
                "field_name": "year_of_manufacture",
                "weight_percent": 20,
                "is_mandatory": False,
                "is_active": True,
                "is_read": False,
                "description": "Gyártási év"
            }
        ]
        
        # Insert weights
        for weight_data in weights:
            weight = SystemDataCompletionWeight(**weight_data)
            db.add(weight)
        
        await db.commit()
        logger.info(f"Successfully seeded {len(weights)} completion weights for entity_type='asset'")
        
        # Log the total percentage
        total = sum(w["weight_percent"] for w in weights)
        logger.info(f"Total weight percentage: {total}%")

async def main():
    """Main entry point."""
    try:
        await seed_completion_weights()
    except Exception as e:
        logger.error(f"Failed to seed completion weights: {e}", exc_info=True)
        raise

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