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

"""
API v2 路由 - 转发到 SaaS 端
"""

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
import requests
import logging
from jingrow.config import Config
from jingrow.utils.auth import get_request_session_cookie

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


def _forward_to_saas(endpoint: str, params: dict = None) -> dict:
    """通用转发函数"""
    url = f"{Config.jingrow_server_url}/api/v2{endpoint}"
    headers = {"Accept": "application/json", "Content-Type": "application/json"}
    
    session_cookie = get_request_session_cookie()
    if session_cookie:
        headers["Cookie"] = f"sid={session_cookie}"
    
    resp = requests.get(url, headers=headers, params=params, timeout=30)
    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):
    """获取 PageType 元数据 - 转发到 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):
    """获取 PageType 计数 - 转发到 SaaS 端"""
    params = dict(request.query_params)
    result = _forward_to_saas(f"/pagetype/{pagetype}/count", params)
    return JSONResponse(content=result)
