import os
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase
from werkzeug.middleware.proxy_fix import ProxyFix

# Configure logging
logging.basicConfig(level=logging.DEBUG)

class Base(DeclarativeBase):
    pass

db = SQLAlchemy(model_class=Base)

# create the app
app = Flask(__name__)
app.secret_key = os.environ.get("SESSION_SECRET", "dev-secret-key-change-in-production")
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)

# configure the database, relative to the app instance folder
database_url = os.environ.get("DATABASE_URL")
if database_url:
    app.config["SQLALCHEMY_DATABASE_URI"] = database_url
else:
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///ecommerce.db"
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {
    "pool_recycle": 300,
    "pool_pre_ping": True,
}
app.config["UPLOAD_FOLDER"] = "static/uploads"
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024  # 16MB max file size

# initialize the app with the extension
db.init_app(app)

with app.app_context():
    # Import models and routes
    import models
    import routes
    
    db.create_all()
    
    # Create default admin user if not exists
    admin = models.Admin.query.filter_by(username='admin').first()
    if not admin:
        admin = models.Admin(username='admin', email='admin@goldenuniforms.com')
        admin.set_password('@sisiafashionhouse30')
        db.session.add(admin)
        db.session.commit()
        logging.info("Default admin user created: admin")
    
    # Initialize Golden Uniforms categories
    new_categories = {
        'Track Suits': ['Kids Track Suits', 'Adults Track Suits', 'School Track Suits', 'Corporate Track Suits'],
        'Sweater': ['Crew Neck Sweater', 'V-Neck Sweater', 'Hooded Sweater', 'School Sweater'],
        'Fleece Jacket': ['Full Zip Fleece', 'Half Zip Fleece', 'Kids Fleece Jacket', 'Corporate Fleece'],
        'T-Shirts': ['Polo T-Shirts', 'Round Neck T-Shirts', 'Kids T-Shirts', 'Corporate Polo'],
    }

    for cat_name, subcats in new_categories.items():
        cat = models.Category.query.filter_by(name=cat_name).first()
        if not cat:
            cat = models.Category(name=cat_name)
            db.session.add(cat)
            db.session.flush()
        for subcat_name in subcats:
            existing = models.Subcategory.query.filter_by(name=subcat_name, category_id=cat.id).first()
            if not existing:
                subcat = models.Subcategory(name=subcat_name, category_id=cat.id)
                db.session.add(subcat)

    db.session.commit()
    logging.info("Golden Uniforms categories initialized")
