"""Allow running as: python -m brynq"""
import sys

# If called with no args, inject "chat" so the runtime CLI launches chat directly
if len(sys.argv) <= 1:
    sys.argv = [sys.argv[0], "chat"]

# First-run ping — anonymous, one-time, no content
def _first_run_ping():
    """Send a single anonymous ping on first launch. No content, no PII."""
    try:
        from pathlib import Path
        marker = Path.home() / ".brynq" / ".first_run_done"
        if marker.exists():
            return
        marker.parent.mkdir(parents=True, exist_ok=True)

        import hashlib, platform, socket, json, urllib.request, threading

        # Anonymous instance ID (hash of hostname + salt, not reversible)
        hostname = socket.gethostname()
        instance_id = hashlib.sha256(f"brynq-{hostname}".encode()).hexdigest()[:12]

        payload = json.dumps({
            "event": "first_run",
            "instance_id": instance_id,
            "platform": platform.system(),
            "python": platform.python_version(),
        }).encode("utf-8")

        def _send():
            try:
                req = urllib.request.Request(
                    "https://api.brynq.ai/v1/telemetry",
                    data=payload,
                    headers={"Content-Type": "application/json"},
                )
                urllib.request.urlopen(req, timeout=5)
            except Exception:
                pass
            # Mark as done regardless of success
            try:
                marker.write_text("1")
            except Exception:
                pass

        # Non-blocking — never delays startup
        threading.Thread(target=_send, daemon=True).start()
    except Exception:
        pass

_first_run_ping()


def _create_desktop_shortcut():
    """Create a desktop shortcut on first install. Windows only, silent."""
    try:
        import platform
        if platform.system() != "Windows":
            return
        from pathlib import Path
        marker = Path.home() / ".brynq" / ".shortcut_done"
        if marker.exists():
            return

        desktop = Path.home() / "Desktop"
        if not desktop.exists():
            return

        shortcut_path = desktop / "Brynq.bat"
        if shortcut_path.exists():
            marker.parent.mkdir(parents=True, exist_ok=True)
            marker.write_text("1")
            return

        # Create a simple .bat that launches Brynq TUI
        shortcut_path.write_text(
            '@echo off\r\n'
            'title Brynq\r\n'
            'python -m brynq tui\r\n',
            encoding="utf-8",
        )

        marker.parent.mkdir(parents=True, exist_ok=True)
        marker.write_text("1")
    except Exception:
        pass


_create_desktop_shortcut()

from runtime.cli import main
main()
