import os
import sys
import webbrowser

from waitress import serve


def _load_dotenv_if_exists():
 
    try:
        from dotenv import load_dotenv
    except Exception:
        return

    exe_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
    for name in ("config.env",):
        env_path = os.path.join(exe_dir, name)
        if os.path.exists(env_path):
            load_dotenv(env_path, override=True)
            break


def main():
    _load_dotenv_if_exists()

    # 注意：必须在加载 config.env 之后再导入 app.py
    # 否则 app.py 顶层读取环境变量（DB/AI 等）时拿不到最新配置
    import app as webapp

    host = os.getenv("WEB_HOST", "127.0.0.1")
    port = int(os.getenv("WEB_PORT", "5000"))

    # 打开浏览器（只在本机访问时打开）
    if host in ("127.0.0.1", "localhost"):
        try:
            webbrowser.open(f"http://127.0.0.1:{port}", new=1)
        except Exception:
            pass

    # 正式服务（比 Flask debug 更稳定）
    try:
        serve(webapp.app, host=host, port=port, threads=8)
    except KeyboardInterrupt:
        print("\n服务已停止")
    except OSError as e:
        if "Address already in use" in str(e) or "只允许使用一次" in str(e):
            print(f"端口 {port} 已被占用，请修改 config.env 中的 WEB_PORT")
        else:
            print(f"服务启动失败: {e}")
        import traceback
        traceback.print_exc()
    except Exception as e:
        print(f"服务启动失败: {e}")
        import traceback
        traceback.print_exc()
    except KeyboardInterrupt:
        print("\n\n服务已停止")
    except OSError as e:
        if "Address already in use" in str(e) or "只允许使用一次" in str(e):
            print(f"\n\n✗ 端口 {port} 已被占用！")
            print(f"   请检查是否有其他程序在使用该端口")
            print(f"   或修改 config.env 中的 WEB_PORT 为其他端口（如 8080）")
        else:
            print(f"\n\n✗ 服务启动失败: {e}")
        import traceback
        traceback.print_exc()
    except Exception as e:
        print(f"\n\n✗ 服务启动失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()


