import sys
import os
import json
# ✅ importar el registrador de blueprints de la app
from apps.wp_invoices import register_blueprints as wpinv_register

# --- Cargar .env temprano (ruta absoluta) ---
ENV_PATH = "/var/www/html/flask_server/.env"
try:
    from dotenv import load_dotenv
    loaded = load_dotenv(dotenv_path=ENV_PATH)
    if not loaded:
        print(f"⚠️  .env no cargado desde {ENV_PATH} (archivo no encontrado o vacío)")
    else:
        print(f"✅ .env cargado desde {ENV_PATH}")
except Exception as e:
    print(f"⚠️  No se pudo cargar .env: {e}")

# --- Entorno Virtual ---
venv_path = "/var/www/html/flask_server/venv"
sys.path.insert(0, os.path.join(venv_path, "lib/python3.10/site-packages"))
os.environ["VIRTUAL_ENV"] = venv_path
os.environ["PATH"] = os.path.join(venv_path, "bin") + os.pathsep + os.environ["PATH"]

# --- Ruta Base ---
base_path = "/var/www/html/flask_server"
sys.path.insert(0, base_path)

# --- Flask App ---
from flask import Flask, request, g, jsonify
from flask_cors import CORS
from urllib.parse import urlparse
from config.base import Config
from config.db import init_db_app

# --- Config Cliente Dinámico ---
from registered_users.tenants import obtener_configuracion_cliente

app = Flask(__name__)


class WPInvoicesConfig:
    WP_INVOICES_UPLOAD_DIR = os.getenv(
        "WP_INVOICES_UPLOAD_DIR",
        "/var/www/html/flask_server/data/wp_invoices/uploads",
    )
    OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
    WP_INVOICES_DEFAULT_DPI = int(os.getenv("WP_INVOICES_DEFAULT_DPI", "220"))


app.config.from_object(WPInvoicesConfig)

app.config["MAX_CONTENT_LENGTH"] = int(os.getenv("MAX_UPLOAD_MB", "20")) * 1024 * 1024
app.config.from_object(Config)
init_db_app(app)

APP_ENV = os.getenv("APP_ENV", "prod")


TENANTS_FILE = os.path.join(base_path, 'registered_users', 'tenants.json')
try:
    with open(TENANTS_FILE, 'r') as f:
        CLIENTES_CONFIG = json.load(f)
except Exception as e:
    print(f"❌ Error cargando tenants.json: {e}")
    CLIENTES_CONFIG = {}


# ✅ registra wp_invoices V1 (UI simple → JSON)
wpinv_register(app)





""" @app.route('/flask/validate-connection', methods=['OPTIONS'])
def options_validate_connection():
    print("🔄 Preflight OPTIONS recibido para /flask/validate-connection")
    response = app.make_default_options_response()
    origin = request.headers.get('Origin', '')
    response.headers['Access-Control-Allow-Origin'] = origin
    response.headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type, X-License-Key'
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    return response


def extraer_dominio_desde_header(dominio_crudo):
    if not dominio_crudo:
        print("⚠️ No se recibió dominio para extraer.")
        return None
    dominio_crudo = dominio_crudo.lower().strip()
    for cliente in CLIENTES_CONFIG:
        if cliente in dominio_crudo:
            return cliente
    print(f"❌ Ningún cliente coincide con el dominio recibido: {dominio_crudo}")
    return None


@app.before_request
def cargar_config_por_subdominio():
    host = request.headers.get("Host", "")
    print(f"📥 Host recibido: {host}")
    cliente_id = extraer_dominio_desde_header(host)


    if not cliente_id and APP_ENV == "dev":
        g.cliente_id = "dev-tenant"
        g.cliente_config = {"secret_key": "insecure_default", "frontend_domain": ""}
        app.config["SECRET_KEY"] = "insecure_default"
        print("🟡 DEV bypass activo: usando tenant dev-tenant")
        return  

    g.cliente_id = cliente_id
    print(f"🔎 Dominio extraído: {cliente_id}")

    if not cliente_id:
        return jsonify({"error": "Dominio no reconocido o no registrado"}), 403

    try:
        g.cliente_config = obtener_configuracion_cliente(cliente_id)
        app.config["SECRET_KEY"] = g.cliente_config.get("secret_key", "insecure_default")
        print(f"✅ Configuración cargada para {cliente_id}")
    except Exception as e:
        print(f"❌ Error cargando config cliente: {e}")
        return jsonify({"error": f"Cliente '{cliente_id}' no válido o no registrado"}), 403


@app.after_request
def aplicar_cors_dinamico(response):
    try:
        origin = request.headers.get("Origin", "")
        print(f"🌐 Origin recibido: {origin}")
        cliente_id = g.get("cliente_id")
        cliente_config = g.get("cliente_config", {})

        dominio_autorizado = cliente_config.get("frontend_domain", "")

        if origin and dominio_autorizado and dominio_autorizado in origin:
            response.headers['Access-Control-Allow-Origin'] = origin
            response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization,X-License-Key'
            response.headers['Access-Control-Allow-Methods'] = 'POST,OPTIONS'
            response.headers['Access-Control-Allow-Credentials'] = 'true'
            print(f"🟢 CORS permitido para {origin}")
        else:
            print(f"🔒 CORS bloqueado para: {origin}")
    except Exception as e:
        print(f"⚠️ Error aplicando CORS dinámico: {e}")

    return response

from routes.ping_routes import ping_routes
from routes.debug_routes import debug_routes
from routes.forms_routes import forms_routes
from apps.wp_orders.routes import wp_orders_routes
from apps.voiceordering_app.routes import voiceordering_routes
from routes.health import bp as health_routes  

app.register_blueprint(ping_routes)
app.register_blueprint(debug_routes)
app.register_blueprint(forms_routes)
app.register_blueprint(wp_orders_routes, url_prefix="/wp_orders")
app.register_blueprint(voiceordering_routes, url_prefix="/voiceordering")
app.register_blueprint(wp_invoices_bp)
app.register_blueprint(health_routes)          

print("🔍 Rutas Flask registradas:")
for rule in app.url_map.iter_rules():
    print(f"➡️ {rule}")



def application(environ, start_response):
    path = environ.get("PATH_INFO", "").strip("/")
    print(f"📍 WSGI Path recibido: {path}")
    return app(environ, start_response) """

# 👇 ESTA LÍNEA ES LA CLAVE PARA APACHE
application = app

if __name__ == "__main__":
    # Permite correr en modo standalone de desarrollo
    app.run(host="127.0.0.1", port=5000, debug=True)
