from __future__ import annotations

import os
import sys
import webbrowser
from pathlib import Path

import streamlit.cli_util as cli_util
from streamlit import config
from streamlit.web import bootstrap


def _resource_root() -> Path:
    if hasattr(sys, "_MEIPASS"):
        return Path(getattr(sys, "_MEIPASS"))
    return Path(__file__).resolve().parent


def _resolve_port(default: int = 8501) -> int:
    raw = os.environ.get("MANESH_TRADER_PORT", str(default))
    try:
        port = int(raw)
    except ValueError:
        return default

    if 1 <= port <= 65535:
        return port
    return default


def _disable_external_browser() -> None:
    # Force any browser launch attempt to no-op in embedded mode.
    webbrowser.open = lambda *_args, **_kwargs: False
    webbrowser.open_new = lambda *_args, **_kwargs: False
    webbrowser.open_new_tab = lambda *_args, **_kwargs: False
    cli_util.open_browser = lambda _url: None


def main() -> None:
    root = _resource_root()
    app_script = root / "app.py"
    if not app_script.exists():
        raise FileNotFoundError(f"Bundled app script not found: {app_script}")

    os.chdir(root)
    os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false")
    os.environ.setdefault("STREAMLIT_DEVELOPMENT_MODE", "false")
    os.environ.setdefault("STREAMLIT_GLOBAL_DEVELOPMENT_MODE", "false")

    port = _resolve_port()
    os.environ["STREAMLIT_SERVER_HEADLESS"] = "true"
    os.environ["STREAMLIT_SERVER_PORT"] = str(port)
    os.environ["STREAMLIT_SERVER_ADDRESS"] = "127.0.0.1"
    os.environ["STREAMLIT_BROWSER_SERVER_ADDRESS"] = "127.0.0.1"
    os.environ["STREAMLIT_BROWSER_SERVER_PORT"] = str(port)

    config.set_option("global.developmentMode", False)
    config.set_option("server.headless", True)
    config.set_option("server.port", port)
    config.set_option("server.address", "127.0.0.1")
    config.set_option("browser.serverAddress", "127.0.0.1")
    config.set_option("browser.serverPort", port)

    _disable_external_browser()

    bootstrap.run(str(app_script), False, [], {})


if __name__ == "__main__":
    main()
