from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.v1 import documents, sources, stats, tasks
from app.config import get_settings
from app.database import init_db
from common_logging import LoggingMiddleware, get_logger, setup_logging
from common_metrics import setup_metrics

settings = get_settings()
setup_logging(level=settings.log_level)
logger = get_logger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    logger.info(f'Starting {settings.app_name} v{settings.app_version}')
    init_db()
    logger.info('Database initialized')
    yield
    logger.info('Shutting down application')
app = FastAPI(title=settings.app_name, version=settings.app_version, description='税务数据采集和处理服务', lifespan=lifespan)
app.add_middleware(LoggingMiddleware)
setup_metrics(app, "data-center")
app.add_middleware(CORSMiddleware, allow_origins=['http://localhost:8500', 'http://localhost:8888', 'http://localhost:8890', 'http://ai.leshuiyun.com', 'https://ai.leshuiyun.com', 'http://data.leshuiyun.com', 'https://data.leshuiyun.com'], allow_credentials=True, allow_methods=['*'], allow_headers=['*'])
app.include_router(tasks.router, prefix='/api/v1/tasks', tags=['任务管理'])
app.include_router(documents.router, prefix='/api/v1/documents', tags=['文档管理'])
app.include_router(stats.router, prefix='/api/v1/stats', tags=['统计信息'])
app.include_router(sources.router, prefix='/api/v1', tags=['sources'])

@app.get('/')
async def root():
    return {'name': settings.app_name, 'version': settings.app_version, "status":"running"}

@app.get('/health')
async def health_check():
    return {'status': 'healthy'}
if __name__ == '__main__':
    import uvicorn
    uvicorn.run('app.main:app', host='0.0.0.0', port=8002, reload=settings.debug, log_level=settings.log_level.lower())
