from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.core.config import settings
from app.api.v1.endpoints import health, auth, files
import uvicorn
from datetime import datetime
import sys
import os

# 简单的日志打印函数
def log_info(message):
    """打印INFO级别日志"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] INFO: {message}")

def log_error(message):
    """打印ERROR级别日志"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] ERROR: {message}")

def log_debug(message):
    """打印DEBUG级别日志"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] DEBUG: {message}")

# 确保logs目录存在
os.makedirs("logs", exist_ok=True)

log_info("=== Test Server Starting ===")
log_info(f"Python version: {sys.version}")
log_info(f"Working directory: {os.getcwd()}")
log_info("Simple print logger configured")

app = FastAPI(
    title="云盘应用 API (测试环境)",
    description="现代化的云存储Web应用后端API - 测试环境",
    version="1.0.0-test",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.ALLOWED_HOSTS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(health.router, prefix="/api/v1", tags=["health"])
app.include_router(auth.router, prefix="/api/v1/auth", tags=["authentication"])
app.include_router(files.router, prefix="/api/v1/files", tags=["files"])

@app.get("/")
async def root():
    return {"message": "云盘应用 API (测试环境)", "version": "1.0.1-test", "port": 8010}

@app.get("/test")
async def test():
    return {"status": "ok", "message": "测试服务器运行正常", "port": 8010}

if __name__ == "__main__":
    # 设置测试端口
    test_port = 8010

    # 临时设置环境变量覆盖配置
    os.environ["PORT"] = str(test_port)

    uvicorn.run(
        "test-main:app",
        host="0.0.0.0",
        port=test_port,
        reload=False  # 测试环境不使用热重载
    )