
import logging
import os
import sys

# Add parent directory to path to allow importing web module
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from web.services.feature_service import FeatureService
from web.config import Config
from web.app import create_app
import sqlite3

# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

L3_DB_PATH = Config.DB_L3_PATH
SCHEMA_PATH = os.path.join(Config.BASE_DIR, 'database', 'L3', 'schema.sql')

def init_db():
    l3_dir = os.path.dirname(L3_DB_PATH)
    if not os.path.exists(l3_dir):
        os.makedirs(l3_dir)
        
    conn = sqlite3.connect(L3_DB_PATH)
    with open(SCHEMA_PATH, 'r', encoding='utf-8') as f:
        conn.executescript(f.read())
    conn.commit()
    conn.close()
    logger.info("L3 DB Initialized/Updated with Schema.")

def main():
    logger.info("Starting L3 Builder (Delegating to FeatureService)...")
    
    # 1. Ensure Schema is up to date
    init_db()
    
    # 2. Rebuild Features using the centralized logic
    try:
        app = create_app()
        with app.app_context():
            count = FeatureService.rebuild_all_features()
            logger.info(f"Successfully rebuilt features for {count} players.")
    except Exception as e:
        logger.error(f"Error rebuilding features: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
