# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
API v2 routes - Forward to SaaS using unified HTTP client
"""

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
import logging
import time
from jingrow.utils.auth import saas_get

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v2")


def _forward_to_saas(endpoint: str, params: dict = None) -> dict:
    """Forward request to SaaS using unified HTTP client"""
    start_time = time.time()
    
    print(f"[v2] Forwarding to: {endpoint}")
    
    resp = saas_get(f"/api/v2{endpoint}", params=params)
    
    req_time = time.time() - start_time
    print(f"[v2] Response: status={resp.status_code}, time={req_time:.3f}s, endpoint={endpoint}")
    
    if resp.status_code == 200:
        return resp.json()
    logger.error(f"[v2] SaaS error {endpoint}: {resp.status_code}")
    return {}


@router.get("/pagetype/{pagetype}/meta")
async def get_meta(pagetype: str):
    """Get PageType metadata - Forward to SaaS"""
    result = _forward_to_saas(f"/pagetype/{pagetype}/meta")
    return JSONResponse(content=result)


@router.get("/pagetype/{pagetype}/count")
async def get_count(pagetype: str, request: Request):
    """Get PageType count - Forward to SaaS"""
    params = dict(request.query_params)
    result = _forward_to_saas(f"/pagetype/{pagetype}/count", params)
    return JSONResponse(content=result)
