import os
from flask import Flask, jsonify
from routes.auth import auth_bp
from flask_jwt_extended import JWTManager
from routes.profile import profile_bp
from routes.clients import clients_bp
from routes.transporters import transporters_bp
from routes.destinations import destinations_bp
from routes.orders_out import orders_bp
from routes.ouders_in import orders_in_bp
from routes.report_order_out import report_order_out_bp
from admin.subscription import admin_subscription_bp
from routes.subscription import subscription_bp
from admin.tenants import admin_user_bp
from routes.company_user import company_user_bp
from routes.currency import currency_bp

from apscheduler.schedulers.background import BackgroundScheduler
from models.subscription import Subscription

from flask_cors import CORS

app = Flask(__name__)
CORS(
    app,
    resources={r"/*": {"origins": [os.getenv("WEB_ORIGIN", "*")]}},
    allow_headers=["Authorization", "Content-Type"],
    expose_headers=["Content-Type"],
)

@app.get("/db/check")
def db_check():
    try:
        import psycopg  # psycopg3 client
    except Exception as e:
        return {"ok": False, "error": f"psycopg not available: {e}"}, 500

    dsn = os.getenv("DATABASE_URL")
    if not dsn:
        return {"ok": False, "error": "DATABASE_URL not set"}, 500

    try:
        with psycopg.connect(dsn, connect_timeout=5) as conn:
            with conn.cursor() as cur:
                cur.execute("SELECT version();")
                ver = cur.fetchone()[0]
        return {"ok": True, "version": ver}, 200
    except Exception as e:
        return {"ok": False, "error": str(e)}, 500

@app.get("/health")
def health():
    return {"ok": True}, 200

app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY", "your-jwt-secret")
app.config["JWT_TOKEN_LOCATION"] = ["headers", "query_string"]
app.config["JWT_QUERY_STRING_NAME"] = "token"
jwt = JWTManager(app)

env = os.environ.get("FLASK_ENV", "development")

# Register blueprints
app.register_blueprint(auth_bp, url_prefix="/auth")
app.register_blueprint(profile_bp, url_prefix="/profile")
app.register_blueprint(clients_bp)
app.register_blueprint(transporters_bp, url_prefix="/transporters")
app.register_blueprint(destinations_bp, url_prefix="/destinations")
app.register_blueprint(orders_bp, url_prefix="/orders")
app.register_blueprint(orders_in_bp, url_prefix="/orders_in")
app.register_blueprint(report_order_out_bp)
app.register_blueprint(admin_subscription_bp)
app.register_blueprint(subscription_bp)
app.register_blueprint(admin_user_bp)
app.register_blueprint(company_user_bp)
app.register_blueprint(currency_bp)

def update_subscription_statuses_job():
    print("[Scheduler] Running daily subscription status check...")
    subscription_model = Subscription()
    subscription_model.update_subscription_statuses()

RUN_SCHEDULER = os.getenv("RUN_SCHEDULER", "1") == "1"

if RUN_SCHEDULER:
    scheduler = BackgroundScheduler(daemon=True)
    scheduler.add_job(func=update_subscription_statuses_job, trigger="interval", days=1)
    scheduler.start()


if __name__ == "__main__":
    if env != "production":
        # Avoid running the scheduler twice in development mode
        import logging
        logging.getLogger("apscheduler").setLevel(logging.DEBUG)

    app.run(debug=(env == "development"), use_reloader=False)