.DEFAULT_GOAL := help

.PHONY: help build build-linux build-bridge run deploy deploy-ext deploy-storefront bridge clean

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}'

build: ## Build Go server binary (macOS)
	cd server && go build -o scraper

build-linux: ## Cross-compile server for Linux (tengxun)
	cd server && GOOS=linux GOARCH=amd64 go build -o scraper .

build-bridge: ## Cross-compile wsbridge for Windows
	cd tools/wsbridge && GOOS=windows GOARCH=amd64 go build -o wsbridge.exe .

run: ## Run Go server locally (port 8080)
	cd server && go run .

deploy: ## Deploy server to tokyo0301 (git pull + build on remote)
	ssh ubuntu@tokyo0301 'cd ~/eh2 && git pull && pkill -x scraper || true; sleep 1 && cd server && /usr/local/go/bin/go build -o ../scraper . && cd ~/eh2 && ADDR=:19527 nohup ./scraper > scraper.log 2>&1 &'
	@echo "Deployed. Check: ssh ubuntu@tokyo0301 'tail -5 ~/eh2/scraper.log'"

deploy-ext: ## Deploy extension to server + reload Chrome plugin
	ssh ubuntu@tokyo0301 'cd ~/eh2 && git pull'
	@curl -sf -X POST http://$(SERVER_IP):19527/api/reload-extension -o /dev/null && echo "Reloaded." || echo "Extension not connected. Will auto-reload within 30s."

deploy-storefront: ## Deploy storefront to tokyo0301 (git pull + build on remote)
	ssh ubuntu@tokyo0301 'cd ~/eh2 && git pull && pkill -x storefront || true; sleep 1 && cd storefront/frontend && npm run build && cd .. && /usr/local/go/bin/go build -o storefront . && ADDR=:19528 nohup ./storefront > storefront.log 2>&1 &'
	@echo "Deployed. Check: ssh ubuntu@tokyo0301 'tail -5 ~/eh2/storefront/storefront.log'"

SERVER_IP ?= 3.112.47.56

ifeq ($(OS),Windows_NT)
  CLIENT   ?= $(COMPUTERNAME)
  BRIDGE_BIN = wsrelay-win.exe
else
  CLIENT   ?= $(shell hostname -s)
  BRIDGE_BIN = wsrelay.exe
endif

bridge: ## Run wsbridge (auto-detects OS, set CLIENT/SERVER_IP to override)
	cd tools/wsbridge && ./$(BRIDGE_BIN) -upstream ws://$(SERVER_IP):19527/ws -client $(CLIENT) -extdir ../../extension

clean: ## Remove built binaries
	rm -f server/scraper tools/wsbridge/wsbridge.exe
	@echo "Images kept in images/. Remove manually if needed."
