"""Entry point for the Ambient macOS menu bar app.

Usage:
    python -m hive_compute.app
    # or via the 'ambient-app' script entry point after install
"""

from __future__ import annotations

import sys
from pathlib import Path

_RUN_BENCHMARK_FLAG = "--run-benchmark"
_BENCHMARK_NO_REPORT_FLAG = "--benchmark-no-report"
_BENCHMARK_LOG_PATH = Path("~/.ambient/logs/app-benchmark.log").expanduser()


def _write_benchmark_log(contents: str) -> None:
    _BENCHMARK_LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
    _BENCHMARK_LOG_PATH.write_text(contents.rstrip() + "\n", encoding="utf-8")


def _run_headless_benchmark(*, report_to_coordinator: bool) -> int:
    from hive_compute.app.benchmark_runner import run_app_benchmark

    try:
        completed = run_app_benchmark(report_to_coordinator=report_to_coordinator)
    except Exception as exc:
        message = f"Benchmark failed: {exc}"
        _write_benchmark_log(message)
        print(message, file=sys.stderr)
        return 1

    sections = [completed.stdout.rstrip()]
    if completed.stderr.strip():
        sections.append("[stderr]\n" + completed.stderr.rstrip())
    rendered = "\n\n".join(section for section in sections if section)
    _write_benchmark_log(rendered or "Benchmark completed without terminal output.")
    if rendered:
        print(rendered)
    return 0


def main() -> None:
    if sys.platform != "darwin":
        print("Ambient worker requires macOS.", file=sys.stderr)
        sys.exit(1)

    benchmark_mode = _RUN_BENCHMARK_FLAG in sys.argv[1:]
    report_to_coordinator = _BENCHMARK_NO_REPORT_FLAG not in sys.argv[1:]

    try:
        from hive_compute.app.onboarding import run_onboarding
        from hive_compute.app.onboarding_state import needs_onboarding
        if not benchmark_mode:
            from hive_compute.app.menu_bar import AmbientApp
    except ModuleNotFoundError as exc:
        print(
            "Ambient.app dependencies are missing. Install with the [app] extra or use the packaged .app bundle.",
            file=sys.stderr,
        )
        raise SystemExit(1) from exc

    if needs_onboarding():
        success = run_onboarding()
        if not success:
            sys.exit(0)

    if benchmark_mode:
        sys.exit(_run_headless_benchmark(report_to_coordinator=report_to_coordinator))

    AmbientApp().run()


if __name__ == "__main__":
    main()
