#!/usr/bin/env python
'''
网站路由器
'''

##############################

import os
import sys
from fastapi import FastAPI, Request
import comm

##############################

app = FastAPI()

def fobj(obj, indent=4):
    '''format obj'''
    import json
    from fastapi.responses import PlainTextResponse
    return PlainTextResponse(json.dumps(obj, indent=indent, ensure_ascii=False, default=str))

# 处理原始请求对象 {path:path}
@app.api_route('/api', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
async def request_info(req: Request):
    query = {}
    json = {}
    form = {}
    file = {}
    body = ''
    query = dict(req.query_params)
    head = dict(req.headers)

    # 根据 Content-Type 处理不同类型的数据
    ct = req.headers.get('content-type', '').lower()
    
    try:
        if 'application/json' in ct:
            # JSON 数据
            json = await req.json()
        elif 'application/x-www-form-urlencoded' in ct:
            # 表单数据
            form = await req.form()
            form = {k: v for k, v in form.items()}
        elif 'multipart/form-data' in ct:
            # 多部分表单（包含文件上传）
            form = await req.form()
            for k, v in form.items():
                if hasattr(v, 'file'):
                    ctt = await v.read()
                    file['ctt'] = ctt
                    file['name'] = v.filename
                    file['type'] = v.content_type
                    file['size'] = len(ctt)
                else:
                    file[k] = v
        else:
            # 其他类型，获取原始数据
            body = (await req.body()).decode('utf-8')
    except Exception as e:
        body = f"Parse Error: {str(e)}"
    
    if 'x-forwarded-for' in req.headers:
        # 如果有代理，取第一个IP
        cip = req.headers['x-forwarded-for'].split(',')[0]
    elif 'x-real-ip' in req.headers:
        cip = req.headers.get('x-real-ip')
    else:
        cip = req.client.host if req.client else '0.0.0.0'

    core = {
        'meth': req.method,
        'url': str(req.url),
        'ref': req.headers.get('referer'),
        'ori': req.headers.get('origin'),
        'host': req.headers.get('host'),
        'chost': req.client.host if req.client else None,
        'ua': req.headers.get('user-agent'),
        'cip': cip
    }
    
    data = {}
    data['test'] = str(__package__)
    data['head'] = head
    data['body'] = str(body)
    data['core'] = core
    objs = [query, json, form, file]
    for o in objs:
        for k, v in o.items():
            data[k] = v

    return fobj(data)