# gateway/app/routes/tenant.py - COMPLETELY UPDATED
"""
Tenant routes for API Gateway - Handles all tenant-scoped endpoints
"""

from fastapi import APIRouter, Request, Response, HTTPException, Path
from fastapi.responses import JSONResponse
import httpx
import logging
from typing import Optional

from app.core.config import settings

logger = logging.getLogger(__name__)
router = APIRouter()

# ================================================================
# TENANT MANAGEMENT ENDPOINTS
# ================================================================

@router.post("/register")
async def create_tenant(request: Request):
    """Proxy tenant creation to tenant service"""
    return await _proxy_to_tenant_service(request, "/api/v1/tenants/register")

@router.get("/{tenant_id}")
async def get_tenant(request: Request, tenant_id: str = Path(...)):
    """Get specific tenant details"""
    return await _proxy_to_tenant_service(request, f"/api/v1/tenants/{tenant_id}")

@router.put("/{tenant_id}")
async def update_tenant(request: Request, tenant_id: str = Path(...)):
    """Update tenant details"""
    return await _proxy_to_tenant_service(request, f"/api/v1/tenants/{tenant_id}")

@router.get("/{tenant_id}/members")
async def get_tenant_members(request: Request, tenant_id: str = Path(...)):
    """Get tenant members"""
    return await _proxy_to_tenant_service(request, f"/api/v1/tenants/{tenant_id}/members")

@router.get("/user/{user_id}")
async def get_user_tenants(request: Request, user_id: str = Path(...)):
    """Get all tenant memberships for a user (admin only)"""
    return await _proxy_to_tenant_service(request, f"/api/v1/tenants/users/{user_id}")

@router.get("/user/{user_id}/owned")
async def get_user_owned_tenants(request: Request, user_id: str = Path(...)):
    """Get all tenants owned by a user"""
    return await _proxy_to_tenant_service(request, f"/api/v1/tenants/user/{user_id}/owned")

@router.delete("/user/{user_id}/memberships")
async def delete_user_tenants(request: Request, user_id: str = Path(...)):
    """Get all tenant memberships for a user (admin only)"""
    return await _proxy_to_tenant_service(request, f"/api/v1/tenants/user/{user_id}/memberships")

# ================================================================
# TENANT SUBSCRIPTION ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/subscriptions/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_subscriptions(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant subscription requests to tenant service"""
    target_path = f"/api/v1/subscriptions/{tenant_id}/{path}".rstrip("/")
    return await _proxy_to_tenant_service(request, target_path)

@router.api_route("/subscriptions/plans", methods=["GET", "OPTIONS"])
async def proxy_available_plans(request: Request):
    """Proxy available plans request to tenant service"""
    target_path = "/api/v1/plans/available"
    return await _proxy_to_tenant_service(request, target_path)

# ================================================================
# TENANT-SCOPED DATA SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/sales{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_all_tenant_sales_alternative(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy all tenant sales requests - handles both base and sub-paths"""
    base_path = f"/api/v1/tenants/{tenant_id}/sales"
    
    # If path is empty or just "/", use base path
    if not path or path == "/" or path == "":
        target_path = base_path
    else:
        # Ensure path starts with "/"
        if not path.startswith("/"):
            path = "/" + path
        target_path = base_path + path
    
    return await _proxy_to_sales_service(request, target_path)

@router.api_route("/{tenant_id}/weather/{path:path}", methods=["GET", "POST", "OPTIONS"])
async def proxy_tenant_weather(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant weather requests to external service"""
    target_path = f"/api/v1/tenants/{tenant_id}/weather/{path}".rstrip("/")
    return await _proxy_to_external_service(request, target_path)

@router.api_route("/{tenant_id}/traffic/{path:path}", methods=["GET", "POST", "OPTIONS"])
async def proxy_tenant_traffic(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant traffic requests to external service"""
    target_path = f"/api/v1/tenants/{tenant_id}/traffic/{path}".rstrip("/")
    return await _proxy_to_external_service(request, target_path)

@router.api_route("/{tenant_id}/analytics/{path:path}", methods=["GET", "POST", "OPTIONS"])
async def proxy_tenant_analytics(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant analytics requests to sales service"""
    target_path = f"/api/v1/tenants/{tenant_id}/analytics/{path}".rstrip("/")
    return await _proxy_to_sales_service(request, target_path)

@router.api_route("/{tenant_id}/onboarding/{path:path}", methods=["GET", "POST", "OPTIONS"])
async def proxy_tenant_analytics(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant analytics requests to sales service"""
    target_path = f"/api/v1/tenants/{tenant_id}/onboarding/{path}".rstrip("/")
    return await _proxy_to_sales_service(request, target_path)

# ================================================================
# TENANT-SCOPED TRAINING SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/training/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_training(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant training requests to training service"""
    target_path = f"/api/v1/tenants/{tenant_id}/training/{path}".rstrip("/")
    return await _proxy_to_training_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/models/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_models(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant model requests to training service"""
    target_path = f"/api/v1/tenants/{tenant_id}/models/{path}".rstrip("/")
    return await _proxy_to_training_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/statistics", methods=["GET", "OPTIONS"])
async def proxy_tenant_statistics(request: Request, tenant_id: str = Path(...)):
    """Proxy tenant statistics requests to training service"""
    target_path = f"/api/v1/tenants/{tenant_id}/statistics"
    return await _proxy_to_training_service(request, target_path, tenant_id=tenant_id)

# ================================================================
# TENANT-SCOPED FORECASTING SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/forecasts/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_forecasts(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant forecast requests to forecasting service"""
    target_path = f"/api/v1/tenants/{tenant_id}/forecasts/{path}".rstrip("/")
    return await _proxy_to_forecasting_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/predictions/{path:path}", methods=["GET", "POST", "OPTIONS"])
async def proxy_tenant_predictions(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant prediction requests to forecasting service"""
    target_path = f"/api/v1/tenants/{tenant_id}/predictions/{path}".rstrip("/")
    return await _proxy_to_forecasting_service(request, target_path)

# ================================================================
# TENANT-SCOPED NOTIFICATION SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/notifications/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_notifications(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant notification requests to notification service"""
    target_path = f"/api/v1/tenants/{tenant_id}/notifications/{path}".rstrip("/")
    return await _proxy_to_notification_service(request, target_path)

# ================================================================
# TENANT-SCOPED INVENTORY SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/alerts{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_alerts(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant alerts requests to inventory service"""
    target_path = f"/api/v1/tenants/{tenant_id}/alerts{path}".rstrip("/")
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/inventory/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_inventory(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant inventory requests to inventory service"""
    # The inventory service expects /api/v1/tenants/{tenant_id}/inventory/{path}
    # Keep the full path structure for inventory service
    target_path = f"/api/v1/tenants/{tenant_id}/inventory/{path}".rstrip("/")
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

# Specific route for ingredients without additional path
@router.api_route("/{tenant_id}/ingredients", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_ingredients_base(request: Request, tenant_id: str = Path(...)):
    """Proxy tenant ingredient requests to inventory service (base path)"""
    target_path = f"/api/v1/tenants/{tenant_id}/ingredients"
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/ingredients/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_ingredients_with_path(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant ingredient requests to inventory service (with additional path)"""
    # The inventory service ingredient endpoints are now tenant-scoped: /api/v1/tenants/{tenant_id}/ingredients/{path}
    # Keep the full tenant path structure
    target_path = f"/api/v1/tenants/{tenant_id}/ingredients/{path}".rstrip("/")
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/stock/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_stock(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant stock requests to inventory service"""
    # The inventory service stock endpoints are now tenant-scoped: /api/v1/tenants/{tenant_id}/stock/{path}
    target_path = f"/api/v1/tenants/{tenant_id}/stock/{path}".rstrip("/")
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/dashboard/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_dashboard(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant dashboard requests to inventory service"""
    # The inventory service dashboard endpoints are tenant-scoped: /api/v1/tenants/{tenant_id}/dashboard/{path}
    target_path = f"/api/v1/tenants/{tenant_id}/dashboard/{path}".rstrip("/")
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/transformations", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_transformations_base(request: Request, tenant_id: str = Path(...)):
    """Proxy tenant transformations requests to inventory service (base path)"""
    target_path = f"/api/v1/tenants/{tenant_id}/transformations"
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/transformations/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_transformations_with_path(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant transformations requests to inventory service (with additional path)"""
    # The inventory service transformations endpoints are tenant-scoped: /api/v1/tenants/{tenant_id}/transformations/{path}
    target_path = f"/api/v1/tenants/{tenant_id}/transformations/{path}".rstrip("/")
    return await _proxy_to_inventory_service(request, target_path, tenant_id=tenant_id)

# ================================================================
# TENANT-SCOPED PRODUCTION SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/production/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_production(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant production requests to production service"""
    target_path = f"/api/v1/tenants/{tenant_id}/production/{path}".rstrip("/")
    return await _proxy_to_production_service(request, target_path, tenant_id=tenant_id)

# ================================================================
# TENANT-SCOPED ORDERS SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/orders/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_orders(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant orders requests to orders service"""
    target_path = f"/api/v1/tenants/{tenant_id}/orders/{path}".rstrip("/")
    return await _proxy_to_orders_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/customers/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_customers(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant customers requests to orders service"""
    target_path = f"/api/v1/tenants/{tenant_id}/customers/{path}".rstrip("/")
    return await _proxy_to_orders_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/procurement/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_procurement(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant procurement requests to orders service"""
    target_path = f"/api/v1/tenants/{tenant_id}/procurement/{path}".rstrip("/")
    return await _proxy_to_orders_service(request, target_path, tenant_id=tenant_id)

# ================================================================
# TENANT-SCOPED SUPPLIER SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/suppliers/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
@router.api_route("/{tenant_id}/suppliers", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_suppliers(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant supplier requests to suppliers service"""
    if path:
        target_path = f"/api/v1/tenants/{tenant_id}/suppliers/{path}".rstrip("/")
    else:
        target_path = f"/api/v1/tenants/{tenant_id}/suppliers"
    return await _proxy_to_suppliers_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/purchase-orders{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_purchase_orders(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant purchase order requests to suppliers service"""
    target_path = f"/api/v1/tenants/{tenant_id}/purchase-orders{path}".rstrip("/")
    return await _proxy_to_suppliers_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/deliveries{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_deliveries(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant delivery requests to suppliers service"""
    target_path = f"/api/v1/tenants/{tenant_id}/deliveries{path}".rstrip("/")
    return await _proxy_to_suppliers_service(request, target_path, tenant_id=tenant_id)

# ================================================================
# TENANT-SCOPED RECIPES SERVICE ENDPOINTS
# ================================================================

@router.api_route("/{tenant_id}/recipes", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_recipes_base(request: Request, tenant_id: str = Path(...)):
    """Proxy tenant recipes requests to recipes service (base path)"""
    target_path = f"/api/v1/tenants/{tenant_id}/recipes"
    return await _proxy_to_recipes_service(request, target_path, tenant_id=tenant_id)

@router.api_route("/{tenant_id}/recipes/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_recipes_with_path(request: Request, tenant_id: str = Path(...), path: str = ""):
    """Proxy tenant recipes requests to recipes service (with additional path)"""
    target_path = f"/api/v1/tenants/{tenant_id}/recipes/{path}".rstrip("/")
    return await _proxy_to_recipes_service(request, target_path, tenant_id=tenant_id)

# ================================================================
# PROXY HELPER FUNCTIONS
# ================================================================

async def _proxy_to_tenant_service(request: Request, target_path: str):
    """Proxy request to tenant service"""
    return await _proxy_request(request, target_path, settings.TENANT_SERVICE_URL)

async def _proxy_to_sales_service(request: Request, target_path: str):
    """Proxy request to sales service"""
    return await _proxy_request(request, target_path, settings.SALES_SERVICE_URL)

async def _proxy_to_external_service(request: Request, target_path: str):
    """Proxy request to external service"""
    return await _proxy_request(request, target_path, settings.EXTERNAL_SERVICE_URL)

async def _proxy_to_training_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to training service"""
    return await _proxy_request(request, target_path, settings.TRAINING_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_to_forecasting_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to forecasting service"""
    return await _proxy_request(request, target_path, settings.FORECASTING_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_to_notification_service(request: Request, target_path: str):
    """Proxy request to notification service"""
    return await _proxy_request(request, target_path, settings.NOTIFICATION_SERVICE_URL)

async def _proxy_to_inventory_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to inventory service"""
    return await _proxy_request(request, target_path, settings.INVENTORY_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_to_production_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to production service"""
    return await _proxy_request(request, target_path, settings.PRODUCTION_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_to_orders_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to orders service"""
    return await _proxy_request(request, target_path, settings.ORDERS_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_to_suppliers_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to suppliers service"""
    return await _proxy_request(request, target_path, settings.SUPPLIERS_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_to_recipes_service(request: Request, target_path: str, tenant_id: str = None):
    """Proxy request to recipes service"""
    return await _proxy_request(request, target_path, settings.RECIPES_SERVICE_URL, tenant_id=tenant_id)

async def _proxy_request(request: Request, target_path: str, service_url: str, tenant_id: str = None):
    """Generic proxy function with enhanced error handling"""
    
    # Handle OPTIONS requests directly for CORS
    if request.method == "OPTIONS":
        return Response(
            status_code=200,
            headers={
                "Access-Control-Allow-Origin": settings.CORS_ORIGINS_LIST,
                "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
                "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID",
                "Access-Control-Allow-Credentials": "true",
                "Access-Control-Max-Age": "86400"
            }
        )
    
    try:
        url = f"{service_url}{target_path}"
        
        # Forward headers and add user/tenant context
        headers = dict(request.headers)
        headers.pop("host", None)
        
        # Add tenant ID header if provided
        if tenant_id:
            headers["X-Tenant-ID"] = tenant_id
        
        # Add user context headers if available
        if hasattr(request.state, 'user') and request.state.user:
            user = request.state.user
            headers["x-user-id"] = str(user.get('user_id', ''))
            headers["x-user-email"] = str(user.get('email', ''))
            headers["x-user-role"] = str(user.get('role', 'user'))
            headers["x-user-full-name"] = str(user.get('full_name', ''))
            headers["x-tenant-id"] = tenant_id or str(user.get('tenant_id', ''))
            # Debug logging
            logger.info(f"Forwarding request to {url} with user context: user_id={user.get('user_id')}, email={user.get('email')}, tenant_id={tenant_id}")
        else:
            # Debug logging when no user context available
            logger.warning(f"No user context available when forwarding request to {url}. request.state.user: {getattr(request.state, 'user', 'NOT_SET')}")
        
        # Get request body if present
        body = None
        if request.method in ["POST", "PUT", "PATCH"]:
            body = await request.body()
        
        # Add query parameters
        params = dict(request.query_params)
        
        timeout_config = httpx.Timeout(
            connect=30.0,    # Connection timeout
            read=600.0,      # Read timeout: 10 minutes (was 30s)
            write=30.0,      # Write timeout
            pool=30.0        # Pool timeout
        )
        
        async with httpx.AsyncClient(timeout=timeout_config) as client:
            response = await client.request(
                method=request.method,
                url=url,
                headers=headers,
                content=body,
                params=params
            )
            
            # Handle different response types
            if response.headers.get("content-type", "").startswith("application/json"):
                try:
                    content = response.json()
                except:
                    content = {"message": "Invalid JSON response from service"}
            else:
                content = response.text
            
            return JSONResponse(
                status_code=response.status_code,
                content=content
            )
            
    except Exception as e:
        logger.error(f"Unexpected error proxying to {service_url}{target_path}: {e}")
        raise HTTPException(
            status_code=500,
            detail="Internal gateway error"
        )