import os
import traceback
from flask import Flask
from .extensions import db, socketio
from .models import User, Category, Product, Order, OrderItem, Expense, ShopSettings, Employee, Attendance, BackupSetting, PurchaseOrder, Coupon, VerificationCode, PosSyncLog
from app_server.utils.security import hash_password
from . import currency_config
from . import config as app_config

def create_app():
    app = Flask(__name__)
    
    # Configuration
    app.config['SECRET_KEY'] = app_config.SECRET_KEY
    app.config['SQLALCHEMY_DATABASE_URI'] = app_config.SQLALCHEMY_DATABASE_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['OTP_LENGTH'] = app_config.OTP_LENGTH
    app.config['OTP_EXPIRY_MINUTES'] = app_config.OTP_EXPIRY_MINUTES
    app.config['OTP_MAX_ATTEMPTS'] = app_config.OTP_MAX_ATTEMPTS
    app.config['OTP_RESEND_COOLDOWN_SECONDS'] = app_config.OTP_RESEND_COOLDOWN_SECONDS
    app.config['SMTP_HOST'] = app_config.SMTP_HOST
    app.config['SMTP_PORT'] = app_config.SMTP_PORT
    app.config['SMTP_USERNAME'] = app_config.SMTP_USERNAME
    app.config['SMTP_PASSWORD'] = app_config.SMTP_PASSWORD
    app.config['SMTP_USE_TLS'] = app_config.SMTP_USE_TLS
    app.config['SMTP_USE_SSL'] = app_config.SMTP_USE_SSL
    app.config['MAIL_FROM'] = app_config.MAIL_FROM
    app.config['REGISTRATION_OTP_DEV_LOG'] = app_config.REGISTRATION_OTP_DEV_LOG
    app.config['SMS_OTP_FALLBACK_ON_FAILURE'] = app_config.SMS_OTP_FALLBACK_ON_FAILURE
    app.config['REGISTRATION_VERIFICATION_GRACE_MINUTES'] = app_config.REGISTRATION_VERIFICATION_GRACE_MINUTES

    # Initialize Extensions
    db.init_app(app)
    socketio.init_app(app)

    @app.context_processor
    def inject_store_currency():
        """All storefront templates: use {{ currency }} and {{ currency_code }} (Rs / PKR by default)."""
        return {
            "currency": currency_config.CURRENCY_DISPLAY,
            "currency_code": currency_config.CURRENCY_CODE,
        }

    # 1. Register Blueprints with Debugging Logic
    try:
        from .api.routes import api_bp
        from .web.routes import web_bp
        
        # API Blueprint (Desktop App ka Rasta)
        app.register_blueprint(api_bp, url_prefix='/api')
        # Web Blueprint (Website ka Rasta)
        app.register_blueprint(web_bp)
        
        print("[SwiftCart] API and Web blueprints registered successfully.")
    except Exception as e:
        print(f"[SwiftCart] BLUEPRINT REGISTRATION ERROR: {e}")
        traceback.print_exc()

    # 2. Create Database & Default Admin
    with app.app_context():
        try:
            db.create_all()
            
            # Check if admin already exists
            admin_user = User.query.filter_by(username='admin').first()
            if not admin_user:
                # 🛡️ FIXED: Ab email ke sath admin create hoga taake IntegrityError na aaye
                new_admin = User(
                    username='admin', 
                    email='admin@swiftcart.com', 
                    password=hash_password('admin'), 
                    role='admin'
                )
                db.session.add(new_admin)
                db.session.commit()
                print("[SwiftCart] Default admin created (username: admin, password: admin).")
        except Exception as e:
            db.session.rollback()
            print(f"[SwiftCart] DATABASE INITIALIZATION ERROR: {e}")
            traceback.print_exc()

    # ✅ Return statement function ke andar hai
    return app