"""CLI tool for NoticeCard server management."""

import os
from pathlib import Path
import click
import uvicorn


@click.group()
@click.version_option(version="0.2.0")
def main():
    """NoticeCard 服务端命令行工具"""
    pass


@main.command()
@click.option("--host", default="0.0.0.0", help="绑定的主机地址")
@click.option("--port", default=3143, type=int, help="绑定的端口号")
@click.option("--dir", "work_dir", default=".", help="工作目录（数据库存储位置）")
@click.option("--reload", is_flag=True, help="启用自动重载（开发模式）")
@click.option("--log-level", default="info", type=click.Choice(["critical", "error", "warning", "info", "debug"]), help="日志级别")
def serve(host: str, port: int, work_dir: str, reload: bool, log_level: str):
    """启动 NoticeCard 服务器"""
    # Resolve working directory
    work_path = Path(work_dir).resolve()
    work_path.mkdir(parents=True, exist_ok=True)
    
    # Set database path
    db_path = work_path / "noticecard.db"
    
    click.echo(f"正在启动 NoticeCard 服务器...")
    click.echo(f"工作目录: {work_path}")
    click.echo(f"数据库: {db_path}")
    click.echo(f"服务地址: http://{host}:{port}")
    click.echo(f"API 文档: http://{host}:{port}/docs")
    click.echo(f"日志级别: {log_level}")
    
    # Set environment variable for database path
    os.environ["NOTICECARD_DB_PATH"] = str(db_path)
    
    if reload:
        # For reload mode, use string path to app factory
        click.echo("开发模式：已启用自动重载")
        uvicorn.run(
            "noticecard.app:create_app",
            host=host,
            port=port,
            reload=reload,
            log_level=log_level,
            factory=True
        )
    else:
        # For production mode, create app instance
        from .app import create_app
        app = create_app(str(db_path))
        uvicorn.run(
            app,
            host=host,
            port=port,
            log_level=log_level
        )


@main.command()
@click.option("--dir", "work_dir", default=".", help="工作目录")
def init(work_dir: str):
    """初始化数据库"""
    work_path = Path(work_dir).resolve()
    work_path.mkdir(parents=True, exist_ok=True)
    
    db_path = work_path / "noticecard.db"
    
    from .models import init_db
    init_db(str(db_path))
    
    click.echo(f"数据库已初始化: {db_path}")


if __name__ == "__main__":
    main()
