"""WebSocket endpoint for IDE ↔ remote command bridge."""

from __future__ import annotations

import asyncio
import json
import logging

from fastapi import APIRouter, WebSocket, WebSocketDisconnect

from dsc_api.services import remote_ws

router = APIRouter()
logger = logging.getLogger(__name__)


def _push_context_background() -> None:
	"""Fire-and-forget push of workspace context to paired mobile sessions."""
	try:
		from dsc_api.routers.remote import _push_workspace_context
		asyncio.ensure_future(_push_workspace_context())
	except Exception:
		pass  # non-fatal


@router.websocket("/ws/remote")
async def remote_websocket(websocket: WebSocket) -> None:
	"""
	Persistent WebSocket for the IDE to receive remote commands.

	The IDE connects on startup and stays connected. When a user on any
	messaging platform triggers an action via the remote chat API, it's
	pushed here.

	The IDE can also send messages back (e.g., scan results, confirmations):
	{ "event": "action_complete", "action_type": "...", "success": true }
	"""
	await websocket.accept()
	await remote_ws.register(websocket)
	logger.info("IDE remote WebSocket connected")

	try:
		# Send initial handshake
		await websocket.send_json({
			"event": "connected",
			"message": "Remote bridge active",
		})

		# Listen for IDE → backend messages (confirmations, status)
		while True:
			data = await websocket.receive_text()
			try:
				msg = json.loads(data)
				event = msg.get("event")

				if event == "action_complete":
					await remote_ws.on_action_complete(msg)
				elif event == "workspace_info":
					path = msg.get("path", "")
					remote_ws.set_workspace_path(path)
					logger.info("IDE workspace: %s", path)
					_push_context_background()
				elif event == "scan_complete":
					findings = msg.get("findings", [])
					remote_ws.set_workspace_findings(findings)
					logger.info("IDE scan complete: %d findings", len(findings))
					_push_context_background()
				elif event == "ping":
					await websocket.send_json({"event": "pong"})
				else:
					logger.debug("Unknown IDE event: %s", event)

			except json.JSONDecodeError:
				logger.warning("Invalid JSON from IDE WebSocket")

	except WebSocketDisconnect:
		logger.info("IDE remote WebSocket disconnected")
	finally:
		await remote_ws.unregister(websocket)
