# Makefile for operating the make_post_sell server using either PyPI packages or source

# Variables (using the current working directory)
VENV_DIR = $(shell pwd)/env
DATA_DIR = $(shell pwd)/data
CONFIG_FILE = development.ini
# Using the provided configuration URL.
CONFIG_URL = https://git.unturf.com/engineering/make-post-sell/make_post_sell/-/raw/master/development.ini

PYTHON   = $(VENV_DIR)/bin/python
PIP      = $(VENV_DIR)/bin/pip
PSERVE   = $(VENV_DIR)/bin/pserve
ALEMBIC  = $(VENV_DIR)/bin/alembic
MPS_INIT = $(VENV_DIR)/bin/initialize_make_post_sell_db

# Default target: show help
.DEFAULT_GOAL := help


# Help target - shows all available commands
help:
	@echo "Make Post Sell - Available Commands"
	@echo "==================================="
	@echo ""
	@echo "SETUP & INSTALLATION:"
	@echo "  make venv                   - Create Python virtual environment"
	@echo "  make config                 - Download configuration file"
	@echo "  make install-from-pypi      - Complete setup using PyPI packages"
	@echo "  make install-from-source    - Complete setup from source (dev mode)"
	@echo "  make install-from-source-prod - Production install from source"
	@echo ""
	@echo "DATABASE:"
	@echo "  make init-db                - Initialize the database"
	@echo ""
	@echo "DEVELOPMENT:"
	@echo "  make serve                  - Start development server with auto-reload"
	@echo "  make test                   - Run test suite"
	@echo "  make test-coverage          - Run tests with coverage report"
	@echo "  make http                   - Start simple HTTP server on port 8000"
	@echo "  make activate               - Show how to activate virtual environment"
	@echo ""
	@echo "CRYPTOCURRENCY (MONERO):"
	@echo "  make check-monero           - Check if Monero tools are installed"
	@echo "  make install-monero         - Install Monero tools automatically"
	@echo "  make monero-wallet-create   - Create new Monero wallet (first time)"
	@echo "  make monero-node            - Start local Monero node (150GB required)"
	@echo "  make monero-wallet          - Start wallet RPC with local node"
	@echo "  make monero-wallet-remote   - Start wallet RPC with remote node (dev)"
	@echo "  make monero-wallet-remote-auth - Start wallet RPC with auth (testing)"
	@echo "  make monero-full-stack      - Show instructions for complete setup"
	@echo "  make crypto-watcher         - Start payment monitoring service"
	@echo "  make crypto-watcher-once    - Run payment check once (testing)"
	@echo ""
	@echo "CRYPTOCURRENCY (DOGECOIN):"
	@echo "  make check-dogecoin         - Check if Dogecoin Core is installed"
	@echo "  make install-dogecoin       - Install Dogecoin Core automatically"
	@echo "  make dogecoin-config        - Create dogecoin.conf for pruned mode"
	@echo "  make dogecoin-node          - Start Dogecoin daemon (pruned mode)"
	@echo "  make dogecoin-node-full     - Start Dogecoin daemon (full blockchain)"
	@echo "  make dogecoin-status        - Check sync status and wallet info"
	@echo "  make dogecoin-check-fee     - Check current transaction fee setting"
	@echo "  make dogecoin-fix-fee       - Fix high transaction fee (sets to 0.001 DOGE)"
	@echo ""
	@echo "WALLET MANAGEMENT:"
	@echo "  make sweep-check            - Check hot wallet balances (dev tool)"
	@echo "  make sweep                  - Sweep funds to cold storage (dev tool)"
	@echo "  make sweep-all              - Sweep ALL Monero wallet funds to cold storage (dust collection)"
	@echo "  make sweep-all-doge         - Sweep ALL Dogecoin wallet funds to cold storage (dust collection)"
	@echo "  make monero-transactions    - View recent wallet transactions"
	@echo ""
	@echo "DOCUMENTATION:"
	@echo "  make docs/state-machine.dot.svg - Generate state machine diagram from .dot file"
	@echo ""
	@echo "CLEANUP:"
	@echo "  make clean                  - Remove virtual environment"
	@echo ""
	@echo "For more info, see README.md and CRYPTO.rst"

docs/state-machine.dot.svg: docs/state-machine.dot
	@echo "Generating state machine diagram from docs/state-machine.dot..."
	dot -Tsvg docs/state-machine.dot -o docs/state-machine.dot.svg
	@echo "✓ Generated docs/state-machine.dot.svg"

# -----------------------------------------------------------------------------
# Environment Setup Targets
# -----------------------------------------------------------------------------

# Create virtual environment if not present.
$(VENV_DIR)/bin/activate:
	@echo "Creating virtual environment in $(VENV_DIR)..."
	python3 -m venv $(VENV_DIR)

venv: $(VENV_DIR)/bin/activate

# Create data directory and download configuration file if missing.
$(DATA_DIR)/$(CONFIG_FILE):
	@echo "Creating data directory in $(DATA_DIR) and downloading configuration file..."
	mkdir -p $(DATA_DIR)
	cd $(DATA_DIR) && wget -O $(CONFIG_FILE) $(CONFIG_URL)

config: $(DATA_DIR)/$(CONFIG_FILE)

# -----------------------------------------------------------------------------
# Package Installation Targets for PyPI Installation
# -----------------------------------------------------------------------------

# Install the make_post_sell core package from PyPI.
install-core: venv
	@echo "Installing make_post_sell core package from PyPI..."
	$(PIP) install make_post_sell

# Install development extras from PyPI.
install-dev: venv
	@echo "Installing make_post_sell development extras from PyPI..."
	$(PIP) install make_post_sell[dev]

# Combined PyPI installation target.
install: install-core install-dev

# -----------------------------------------------------------------------------
# Package Installation Targets for Source Installation
# -----------------------------------------------------------------------------

# Install from source (editable mode) for development and testing.
install-source-dev-and-test: venv
	@echo "Ensuring setuptools is installed (required by Pyramid on Python 3.12+)..."
	$(PIP) install 'setuptools<81'
	@echo "Installing make_post_sell from source (editable mode) for development..."
	$(PIP) install --editable .
	$(PIP) install --upgrade -r requirements-dev.txt
	$(PIP) install --upgrade -r requirements-test.txt

# Install from source for production (non‑editable).
install-source-prod: venv
	@echo "Ensuring setuptools is installed (required by Pyramid on Python 3.12+)..."
	$(PIP) install 'setuptools<81'
	@echo "Deleting tests from source code for production..."
	rm -rf make_post_sell/tests
	@echo "Installing make_post_sell from source for production (non‑editable)..."
	$(PIP) install .
	$(PIP) install --upgrade -r requirements-prod.txt

# -----------------------------------------------------------------------------
# Database Initialization and Server Targets
# -----------------------------------------------------------------------------

# Initialize the database using the configuration file.
init-db: venv config
	@echo "Initializing the make_post_sell database..."
	$(MPS_INIT) $(DATA_DIR)/$(CONFIG_FILE)
	$(ALEMBIC) -c $(DATA_DIR)/$(CONFIG_FILE) stamp head

# Create a new Alembic migration with a proper auto-generated revision ID.
# Usage: make migration m="description of change"
# Autogenerate compares current models against DB schema and writes the diff.
# ALWAYS use this — NEVER hand-write revision IDs.
migration: venv config
	@if [ -z "$(m)" ]; then echo "ERROR: provide a message: make migration m=\"add foo column\""; exit 1; fi
	$(ALEMBIC) -c $(DATA_DIR)/$(CONFIG_FILE) revision --autogenerate -m "$(m)"

# Apply all pending Alembic migrations.
migrate: venv config
	$(ALEMBIC) -c $(DATA_DIR)/$(CONFIG_FILE) upgrade head

# Show current migration status.
migration-status: venv config
	$(ALEMBIC) -c $(DATA_DIR)/$(CONFIG_FILE) current
	$(ALEMBIC) -c $(DATA_DIR)/$(CONFIG_FILE) history --verbose

# Start the development server.
serve: venv config
	$(PSERVE) $(DATA_DIR)/$(CONFIG_FILE) --reload

# -----------------------------------------------------------------------------
# Combined Setup Targets
# -----------------------------------------------------------------------------

# Install and set up using PyPI packages.
install-from-pypi: venv config install init-db

# Install and set up from source (editable mode) for development and testing.
install-from-source: venv config install-source-dev-and-test init-db

# Install and set up from source for production (non‑editable).
install-from-source-prod: venv config install-source-prod init-db

# -----------------------------------------------------------------------------
# Additional Targets
# -----------------------------------------------------------------------------

# Print instructions for activating the virtual environment.
activate:
	@echo "To activate the virtual environment, run:"
	@echo "  source $(VENV_DIR)/bin/activate"

# Run the test suite.
test: install-source-dev-and-test
	@echo "Running tests in parallel..."
	$(VENV_DIR)/bin/py.test -n auto

# Run tests with coverage for the full repository.
test-coverage: install-source-dev-and-test
	@echo "Running tests with coverage..."
	$(VENV_DIR)/bin/py.test --cov=make_post_sell --cov-report=term-missing --cov-report=html

# Start a simple HTTP server (if needed for static files).
http: venv
	@echo "Starting simple HTTP server on port 8000..."
	$(PYTHON) -m http.server 8000

# Run the crypto watcher service for monitoring crypto payments.
crypto-watcher: venv config
	@echo "Starting crypto payment watcher..."
	@echo "💡 TIP: If Dogecoin refunds fail, check fee: make dogecoin-check-fee"
	$(VENV_DIR)/bin/crypto_watcher $(DATA_DIR)/$(CONFIG_FILE)

# Run the crypto watcher once (for testing or manual processing).
crypto-watcher-once: venv config
	@echo "Running crypto payment watcher once..."
	$(VENV_DIR)/bin/crypto_watcher $(DATA_DIR)/$(CONFIG_FILE) --once

# Check hot wallet balances (dev/admin tool)
sweep-check: venv config
	@echo "Use these alternatives for development/testing:"
	@echo "  make sweep-all           # For Monero (XMR)"
	@echo "  make sweep-all-doge      # For Dogecoin (DOGE)"

# Sweep excess funds to cold storage (dev/admin tool)
sweep: venv config
	@echo "Use these alternatives for development/testing:"
	@echo "  make sweep-all           # For Monero (XMR)"
	@echo "  make sweep-all-doge      # For Dogecoin (DOGE)"

# View recent wallet transactions (requires wallet RPC running)
monero-transactions:
	@echo "Recent Monero wallet transactions:"
	@curl --digest -u "test_user:test_pass" -s -X POST http://127.0.0.1:18083/json_rpc \
		-H 'Content-Type: application/json' \
		-d '{"jsonrpc":"2.0","id":"0","method":"get_transfers","params":{"in":true,"out":true}}' | \
		python3 -c "import sys, json; data = json.load(sys.stdin); print(json.dumps(data, indent=2))"

# Sweep ALL wallet funds to cold storage (dust collection)
sweep-all: venv config
	@echo "=== SWEEPING ALL MONERO WALLET FUNDS TO COLD STORAGE ==="
	@echo "CAUTION: This will send ALL unlocked balance from ALL accounts!"
	@echo ""
	@if [ -z "$${COLD_WALLET_ADDRESS}" ]; then \
		echo "ERROR: COLD_WALLET_ADDRESS environment variable not set!"; \
		echo "Usage: COLD_WALLET_ADDRESS=<your-address> make sweep-all"; \
		exit 1; \
	fi
	@echo "Checking ALL account balances..."
	@all_balance=$$(curl --digest -u "test_user:test_pass" -s -X POST http://127.0.0.1:18083/json_rpc \
		-H 'Content-Type: application/json' \
		-d '{"jsonrpc":"2.0","id":"0","method":"get_balance","params":{"all_accounts":true}}' | \
		python3 -c "import sys, json; d=json.load(sys.stdin); result = d.get('result', {}); total_balance = result.get('balance', 0); total_unlocked = result.get('unlocked_balance', 0); accounts = result.get('per_subaddress', []); print('Total balance: {} atomic units ({:.12f} XMR)'.format(total_balance, total_balance/1e12)); print('Total unlocked: {} atomic units ({:.12f} XMR)'.format(total_unlocked, total_unlocked/1e12)); print('Per account breakdown:'); [print('  Account {}:{} - Balance: {:.12f} XMR (unlocked: {:.12f} XMR)'.format(acc.get('account_index', 0), acc.get('address_index', 0), acc.get('balance', 0)/1e12, acc.get('unlocked_balance', 0)/1e12)) for acc in accounts if acc.get('balance', 0) > 0]; print(total_unlocked)"); \
	total_unlocked=$$(echo "$$all_balance" | tail -1); \
	if [ -z "$$total_unlocked" ] || [ "$$total_unlocked" = "0" ]; then \
		echo "No unlocked balance to sweep across all accounts!"; \
		exit 1; \
	fi; \
	echo ""; \
	echo "Target address: $${COLD_WALLET_ADDRESS}"; \
	echo ""; \
	read -p "Are you sure you want to sweep ALL unlocked funds from ALL accounts? (yes/no): " confirm; \
	if [ "$$confirm" != "yes" ]; then \
		echo "Cancelled."; \
		exit 0; \
	fi; \
	echo ""; \
	echo "Getting all accounts for sweeping..."; \
	accounts=$$(curl --digest -u "test_user:test_pass" -s -X POST http://127.0.0.1:18083/json_rpc \
		-H 'Content-Type: application/json' \
		-d '{"jsonrpc":"2.0","id":"0","method":"get_accounts"}' | \
		python3 -c "import sys, json; d=json.load(sys.stdin); accounts = d.get('result', {}).get('subaddress_accounts', []); account_indices = [acc.get('account_index', 0) for acc in accounts]; print(','.join(map(str, account_indices)))"); \
	echo "Found accounts: $$accounts"; \
	echo ""; \
	for account in $$(echo $$accounts | tr ',' ' '); do \
		echo "Sweeping account $$account..."; \
		response=$$(curl --digest -u "test_user:test_pass" -s -X POST http://127.0.0.1:18083/json_rpc \
			-H 'Content-Type: application/json' \
			-d "{\"jsonrpc\":\"2.0\",\"id\":\"0\",\"method\":\"sweep_all\",\"params\":{\"address\":\"$${COLD_WALLET_ADDRESS}\",\"account_index\":$$account,\"subaddr_indices\":[],\"priority\":0,\"get_tx_metadata\":false}}"); \
		echo "$$response" | python3 -c "import sys, json; d=json.load(sys.stdin); r=d.get('result',{}); amounts=r.get('amount_list',[]); fees=r.get('fee_list',[]); hashes=r.get('tx_hash_list',[]); [print('✓ Account $$account: {:.12f} XMR (fee: {:.12f}) Hash: {}'.format(amt/1e12, fee/1e12, tx_hash)) for amt, fee, tx_hash in zip(amounts, fees, hashes)] if amounts else print('Account $$account: No funds') if 'error' not in d else print('Account $$account:', d['error'].get('message','Error'))"; \
	done; \
	echo ""; \
	echo "All account sweep operations completed!"

# Sweep ALL Dogecoin wallet funds to cold storage (dust collection)
sweep-all-doge: check-dogecoin
	@echo "=== SWEEPING ALL DOGECOIN WALLET FUNDS TO COLD STORAGE ==="
	@echo "CAUTION: This will send ALL unlocked balance from wallet!"
	@echo ""
	@if [ -z "$${COLD_WALLET_ADDRESS}" ]; then \
		echo "ERROR: COLD_WALLET_ADDRESS environment variable not set!"; \
		echo "Usage: COLD_WALLET_ADDRESS=<doge-address> make sweep-all-doge"; \
		exit 1; \
	fi
	@echo "Checking wallet balance..."
	@if ! dogecoin-cli getwalletinfo >/dev/null 2>&1; then \
		echo "❌ Dogecoin wallet not accessible. Is dogecoind running?"; \
		echo "Start with: make dogecoin-node"; \
		exit 1; \
	fi
	@balance=$$(dogecoin-cli getbalance); \
	unconfirmed=$$(dogecoin-cli getunconfirmedbalance || echo "0"); \
	if [ "$$(echo "$$balance == 0" | bc -l)" = "1" ]; then \
		echo "No spendable balance to sweep!"; \
		echo "Balance: $$balance DOGE"; \
		echo "Unconfirmed: $$unconfirmed DOGE"; \
		exit 1; \
	fi; \
	echo "Spendable balance: $$balance DOGE"; \
	echo "Unconfirmed: $$unconfirmed DOGE"; \
	echo ""; \
	echo "Target address: $${COLD_WALLET_ADDRESS}"; \
	echo ""; \
	read -p "Are you sure you want to sweep ALL spendable funds? (yes/no): " confirm; \
	if [ "$$confirm" != "yes" ]; then \
		echo "Cancelled."; \
		exit 0; \
	fi; \
	echo ""; \
	echo "Sweeping $$balance DOGE to cold storage..."; \
	txid=$$(dogecoin-cli sendtoaddress "$${COLD_WALLET_ADDRESS}" $$balance "" "" true); \
	if [ $$? -eq 0 ]; then \
		echo "✓ Sweep successful!"; \
		echo "Amount: $$balance DOGE"; \
		echo "Transaction ID: $$txid"; \
		echo ""; \
		echo "New wallet balance:"; \
		dogecoin-cli getbalance; \
	else \
		echo "❌ Sweep failed!"; \
		exit 1; \
	fi

# -----------------------------------------------------------------------------
# Monero Infrastructure Targets
# -----------------------------------------------------------------------------

# Start the Monero daemon (blockchain node) - requires ~150GB disk space
monero-node: venv config check-monero
	@echo "Starting Monero daemon (monerod)..."
	@echo "This will download ~150GB blockchain data and may take 1-2 days to sync"
	@mkdir -p $(DATA_DIR)/monero-blockchain
	@echo "Checking available disk space..."
	@available=$$(df -BG $(DATA_DIR) | tail -1 | awk '{print $$4}' | sed 's/G//'); \
	if [ $$available -lt 200 ]; then \
		echo "ERROR: Insufficient disk space!"; \
		echo "Available: $${available}GB"; \
		echo "Required: 200GB+ (150GB blockchain + growth)"; \
		exit 1; \
	else \
		echo "Disk space OK: $${available}GB available"; \
	fi
	@echo "Check sync status at: http://127.0.0.1:18081/get_info"
	@echo "Press Ctrl+C to stop"
	monerod --data-dir=$(DATA_DIR)/monero-blockchain \
		--rpc-bind-ip=127.0.0.1 \
		--rpc-bind-port=18081 \
		--confirm-external-bind \
		--log-level=1

# Start the Monero wallet RPC (requires monerod or remote node)
monero-wallet: venv config check-monero
	@echo "Starting Monero wallet RPC..."
	@echo "Make sure monerod is running and synced first!"
	@echo "Wallet file: $(DATA_DIR)/mps-wallet"
	@echo "RPC will be available at: http://127.0.0.1:18083"
	monero-wallet-rpc \
		--wallet-file=$(DATA_DIR)/mps-wallet \
		--password-file=$(DATA_DIR)/wallet-password.txt \
		--rpc-bind-ip=127.0.0.1 \
		--rpc-bind-port=18083 \
		--disable-rpc-login \
		--daemon-address=127.0.0.1:18081 \
		--trusted-daemon \
		--log-level=1

# Development mode - use remote node (no blockchain download needed)
monero-wallet-remote: venv config check-monero
	@echo "Starting wallet with REMOTE node (development/testing only)..."
	@echo "Using public node - less private but no blockchain download"
	@echo "Wallet file: $(DATA_DIR)/mps-wallet"
	@echo "RPC will be available at: http://127.0.0.1:18083"
	@echo ""
	@echo "Trying primary node: opennode.xmr-tw.org:18089"
	monero-wallet-rpc \
		--wallet-file=$(DATA_DIR)/mps-wallet \
		--password-file=$(DATA_DIR)/wallet-password.txt \
		--rpc-bind-ip=127.0.0.1 \
		--rpc-bind-port=18083 \
		--disable-rpc-login \
		--daemon-address=opennode.xmr-tw.org:18089 \
		--trusted-daemon \
		--log-level=1

# Development mode with RPC authentication for testing Digest auth
monero-wallet-remote-auth: venv config check-monero
	@echo "Starting wallet with REMOTE node and RPC AUTHENTICATION..."
	@echo "This enables RPC login for testing Digest authentication"
	@echo "Wallet file: $(DATA_DIR)/mps-wallet"  
	@echo "RPC will be available at: http://127.0.0.1:18083"
	@echo "RPC User: test_user"
	@echo "RPC Pass: test_pass"
	@echo ""
	@echo "Using remote node: opennode.xmr-tw.org:18089"
	monero-wallet-rpc \
		--wallet-file=$(DATA_DIR)/mps-wallet \
		--password-file=$(DATA_DIR)/wallet-password.txt \
		--rpc-bind-ip=127.0.0.1 \
		--rpc-bind-port=18083 \
		--rpc-login=test_user:test_pass \
		--daemon-address=opennode.xmr-tw.org:18089 \
		--trusted-daemon \
		--log-level=1


# Install Monero tools automatically
install-monero:
	@echo "Installing Monero tools..."
	@if [ "$$(uname)" = "Linux" ]; then \
		mkdir -p $(HOME)/.local/bin && \
		cd /tmp && \
		wget -q --show-progress https://downloads.getmonero.org/cli/linux64 && \
		tar -xf linux64 && \
		cp monero-x*/monero* $(HOME)/.local/bin/ && \
		rm -rf monero-x* linux64 && \
		echo "✓ Monero tools installed to $(HOME)/.local/bin/" && \
		echo "" && \
		echo "Add to your PATH by running:" && \
		echo "  export PATH=\"$(HOME)/.local/bin:\$$PATH\"" && \
		echo "Or add that line to your ~/.bashrc or ~/.zshrc" && \
		echo "" && \
		echo "Then run 'make monero-wallet-create' to create a wallet"; \
	elif [ "$$(uname)" = "Darwin" ]; then \
		if command -v brew >/dev/null 2>&1; then \
			brew install monero; \
		else \
			echo "Please install Homebrew first: https://brew.sh"; \
			exit 1; \
		fi; \
	else \
		echo "Unsupported OS. Please download manually from:"; \
		echo "https://www.getmonero.org/downloads/"; \
		exit 1; \
	fi

# Check if Monero tools are installed and provide install instructions
check-monero:
	@if command -v monero-wallet-rpc >/dev/null 2>&1; then \
		echo "✓ Monero tools found: $$(monero-wallet-rpc --version | head -1)"; \
	else \
		echo "❌ Monero tools not found!"; \
		echo ""; \
		if [ "$$(uname)" = "Linux" ]; then \
			echo "Install on Linux:"; \
			echo "Download latest official release (recommended):"; \
			echo "  wget https://downloads.getmonero.org/cli/linux64"; \
			echo "  tar -xf linux64 && sudo cp monero-x*/monero* /usr/local/bin/"; \
			echo ""; \
			echo "Or install to user directory (no sudo):"; \
			echo "  mkdir -p $$HOME/.local/bin"; \
			echo "  wget https://downloads.getmonero.org/cli/linux64"; \
			echo "  tar -xf linux64 && cp monero-x*/monero* $$HOME/.local/bin/"; \
			echo "  export PATH=\"$$HOME/.local/bin:$$PATH\""; \
		elif [ "$$(uname)" = "Darwin" ]; then \
			echo "Install on macOS:"; \
			echo "  brew install monero"; \
			echo ""; \
			echo "Or download latest official release:"; \
			echo "  wget https://downloads.getmonero.org/cli/mac64"; \
			echo "  tar -xf mac64 && sudo cp monero-x*/monero* /usr/local/bin/"; \
		else \
			echo "Download latest official Monero CLI tools:"; \
			echo "  https://www.getmonero.org/downloads/"; \
			echo "  Extract and copy monero-* binaries to /usr/local/bin/"; \
		fi; \
		echo ""; \
		echo "Package managers may have older versions. Official downloads are recommended."; \
		echo "After installing, run this command again."; \
		exit 1; \
	fi

# Create a new Monero wallet for the shop
monero-wallet-create: check-monero
	@echo "Creating new Monero wallet..."
	@echo "IMPORTANT: Save the 25-word mnemonic seed that will be displayed!"
	@echo "Enter a password for the wallet (or leave empty):"
	@read -s password; echo $$password > $(DATA_DIR)/wallet-password.txt
	monero-wallet-cli --generate-new-wallet=$(DATA_DIR)/mps-wallet \
		--password-file=$(DATA_DIR)/wallet-password.txt
	@echo "Wallet created at: $(DATA_DIR)/mps-wallet"
	@echo "Password saved in: $(DATA_DIR)/wallet-password.txt"
	@echo "Now run 'make monero-wallet' or 'make monero-wallet-remote' to start the RPC server"

# Instructions for running the full Monero stack
monero-full-stack:
	@echo "=== Running Full Monero Payment Stack ==="
	@echo ""
	@echo "For PRODUCTION (most secure, requires ~150GB):"
	@echo "  Terminal 1: make monero-node          # Start blockchain node"
	@echo "  Terminal 2: make monero-wallet        # Start wallet RPC (after node syncs)"
	@echo "  Terminal 3: make crypto-watcher       # Start payment watcher"
	@echo "  Terminal 4: make serve                # Start web application"
	@echo ""
	@echo "For DEVELOPMENT (quick start, uses public node):"
	@echo "  Terminal 1: make monero-wallet-remote # Start wallet with remote node"
	@echo "  Terminal 2: make crypto-watcher       # Start payment watcher"
	@echo "  Terminal 3: make serve                # Start web application"
	@echo ""
	@echo "First time? Run 'make monero-wallet-create' to create a wallet"

# -----------------------------------------------------------------------------
# Dogecoin Infrastructure Targets
# -----------------------------------------------------------------------------

# Check if Dogecoin Core is installed and provide install instructions
check-dogecoin:
	@if command -v dogecoind >/dev/null 2>&1; then \
		echo "✓ Dogecoin Core found: $$(dogecoind --version | head -1)"; \
	else \
		echo "❌ Dogecoin Core not found!"; \
		echo ""; \
		echo "Install options:"; \
		echo "1. Automatic: make install-dogecoin"; \
		echo "2. Manual: Download from https://github.com/dogecoin/dogecoin/releases"; \
		echo ""; \
		echo "See DOGECOIN_SETUP.md for detailed instructions"; \
		exit 1; \
	fi

# Install Dogecoin Core automatically
install-dogecoin:
	@echo "Installing Dogecoin Core..."
	@if [ "$$(uname)" = "Linux" ]; then \
		mkdir -p $(HOME)/.local/bin && \
		cd /tmp && \
		echo "Downloading Dogecoin Core v1.14.6..." && \
		wget -q --show-progress https://github.com/dogecoin/dogecoin/releases/download/v1.14.6/dogecoin-1.14.6-x86_64-linux-gnu.tar.gz && \
		tar -xzf dogecoin-1.14.6-x86_64-linux-gnu.tar.gz && \
		cp dogecoin-1.14.6/bin/* $(HOME)/.local/bin/ && \
		rm -rf dogecoin-1.14.6* && \
		echo "✓ Dogecoin Core installed to $(HOME)/.local/bin/" && \
		echo "" && \
		echo "Add to your PATH by running:" && \
		echo "  export PATH=\"$(HOME)/.local/bin:\$$PATH\"" && \
		echo "Or add that line to your ~/.bashrc or ~/.zshrc" && \
		echo "" && \
		echo "Then run 'make dogecoin-config' to create configuration"; \
	elif [ "$$(uname)" = "Darwin" ]; then \
		if command -v brew >/dev/null 2>&1; then \
			brew install dogecoin; \
		else \
			echo "Please install Homebrew first: https://brew.sh"; \
			echo "Or download manually from: https://github.com/dogecoin/dogecoin/releases"; \
			exit 1; \
		fi; \
	else \
		echo "Unsupported OS. Please download manually from:"; \
		echo "https://github.com/dogecoin/dogecoin/releases"; \
		exit 1; \
	fi

# Create dogecoin.conf for pruned hot wallet mode
dogecoin-config: check-dogecoin
	@echo "Creating Dogecoin configuration for hot wallet (pruned mode)..."
	@mkdir -p $(HOME)/.dogecoin
	@if [ -f $(HOME)/.dogecoin/dogecoin.conf ]; then \
		echo "Backing up existing config to dogecoin.conf.backup"; \
		cp $(HOME)/.dogecoin/dogecoin.conf $(HOME)/.dogecoin/dogecoin.conf.backup; \
	fi
	@echo "# Dogecoin Core Configuration for Make Post Sell Hot Wallet" > $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Generated by: make dogecoin-config" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Enable server mode for RPC" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "server=1" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "daemon=1" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# RPC credentials - CHANGE THESE IN PRODUCTION!" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "rpcuser=mps_doge_user" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "rpcpassword=change_this_password_in_production" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "rpcallowip=127.0.0.1" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "rpcport=22555" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# PRUNED MODE - keeps only ~2GB instead of 50GB!" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "prune=2000" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Connect to reliable peers for faster sync" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "addnode=seed.dogechain.info" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "addnode=seed.multidoge.org" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "addnode=seed.dogecoin.com" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Hot wallet for Make Post Sell" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "wallet=make_post_sell_hot_wallet" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Transaction fee settings" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Set reasonable fee for multi-output transactions (sendmany)" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "paytxfee=0.001" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "# Minimum fee per KB (prevents 0-fee transactions)" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo "mintxfee=0.001" >> $(HOME)/.dogecoin/dogecoin.conf
	@echo ""
	@echo "✓ Configuration created at: $(HOME)/.dogecoin/dogecoin.conf"
	@echo ""
	@echo "🔐 SECURITY WARNING: Change the RPC password before production use!"
	@echo "Edit $(HOME)/.dogecoin/dogecoin.conf and update rpcpassword"
	@echo ""
	@echo "Next steps:"
	@echo "1. make dogecoin-node       # Start pruned node (recommended)"
	@echo "2. make dogecoin-status     # Check sync progress"

# Start Dogecoin daemon in pruned mode (recommended)
dogecoin-node: check-dogecoin
	@echo "Starting Dogecoin daemon in PRUNED mode..."
	@echo "This will use ~2GB storage instead of 50GB full blockchain"
	@echo "Initial sync takes 2-4 hours (much faster than full node)"
	@echo ""
	@if [ ! -f $(HOME)/.dogecoin/dogecoin.conf ]; then \
		echo "No config found. Run 'make dogecoin-config' first."; \
		exit 1; \
	fi
	@echo "Data directory: $(HOME)/.dogecoin/"
	@echo "RPC available at: http://127.0.0.1:22555"
	@echo "Check sync status: make dogecoin-status"
	@echo "Press Ctrl+C to stop"
	@echo ""
	dogecoind

# Start Dogecoin daemon in full mode (complete blockchain)
dogecoin-node-full: check-dogecoin
	@echo "Starting Dogecoin daemon in FULL mode..."
	@echo "This will download the complete ~50GB blockchain"
	@echo "Initial sync takes 8-12 hours"
	@echo ""
	@mkdir -p $(DATA_DIR)/dogecoin-blockchain
	@echo "Checking available disk space..."
	@available=$$(df -BG $(DATA_DIR) | tail -1 | awk '{print $$4}' | sed 's/G//'); \
	if [ $$available -lt 60 ]; then \
		echo "ERROR: Insufficient disk space!"; \
		echo "Available: $${available}GB"; \
		echo "Required: 60GB+ (50GB blockchain + growth)"; \
		exit 1; \
	else \
		echo "Disk space OK: $${available}GB available"; \
	fi
	@echo "Data directory: $(DATA_DIR)/dogecoin-blockchain"
	@echo "RPC available at: http://127.0.0.1:22555"
	@echo "Check sync status: make dogecoin-status"
	@echo "Press Ctrl+C to stop"
	@echo ""
	dogecoind -datadir=$(DATA_DIR)/dogecoin-blockchain \
		-rpcbind=127.0.0.1 \
		-rpcport=22555 \
		-rpcuser=mps_doge_user \
		-rpcpassword=change_this_password_in_production \
		-rpcallowip=127.0.0.1 \
		-server=1

# Check and fix Dogecoin transaction fee
dogecoin-check-fee: check-dogecoin
	@echo "=== Checking Dogecoin Transaction Fee ==="
	@if ! dogecoin-cli getwalletinfo >/dev/null 2>&1; then \
		echo "❌ Dogecoin daemon not running"; \
		echo "Start with: make dogecoin-node"; \
		exit 1; \
	fi
	@fee=$$(dogecoin-cli getwalletinfo | grep paytxfee | awk '{print $$2}' | tr -d ','); \
	echo "Current transaction fee: $$fee DOGE"; \
	if [ "$$(echo "$$fee > 0.001" | bc -l)" = "1" ]; then \
		echo "⚠️  WARNING: Transaction fee is too high!"; \
		echo "This may cause sendmany (multi-output transactions) to fail."; \
		echo "Run 'make dogecoin-fix-fee' to set reasonable fee."; \
	else \
		echo "✓ Transaction fee is reasonable"; \
	fi

# Set reasonable Dogecoin transaction fee
dogecoin-fix-fee: check-dogecoin
	@echo "=== Setting Dogecoin Transaction Fee ==="
	@if ! dogecoin-cli getwalletinfo >/dev/null 2>&1; then \
		echo "❌ Dogecoin daemon not running"; \
		echo "Start with: make dogecoin-node"; \
		exit 1; \
	fi
	@echo "Setting transaction fee to 0.001 DOGE..."
	@dogecoin-cli settxfee 0.001
	@echo "✓ Transaction fee updated"
	@echo "New fee: $$(dogecoin-cli getwalletinfo | grep paytxfee | awk '{print $$2}' | tr -d ',') DOGE"

# Check Dogecoin sync status and wallet info
dogecoin-status: check-dogecoin
	@echo "=== Dogecoin Node Status ==="
	@echo ""
	@if ! dogecoin-cli getblockchaininfo >/dev/null 2>&1; then \
		echo "❌ Dogecoin daemon not running or not responding"; \
		echo "Start with: make dogecoin-node"; \
		exit 1; \
	fi
	@echo "Blockchain info:"
	@dogecoin-cli getblockchaininfo | grep -E "(chain|blocks|headers|verificationprogress|size_on_disk|pruned)"
	@echo ""
	@echo "Network info:"
	@dogecoin-cli getnetworkinfo | grep -E "(version|subversion|connections)"
	@echo ""
	@echo "Wallet info:"
	@dogecoin-cli getwalletinfo | grep -E "(walletname|balance|unconfirmed_balance)" || echo "No wallet loaded"
	@echo ""
	@blocks=$$(dogecoin-cli getblockchaininfo | grep '"blocks"' | cut -d: -f2 | tr -d ' ,'); \
	headers=$$(dogecoin-cli getblockchaininfo | grep '"headers"' | cut -d: -f2 | tr -d ' ,'); \
	if [ "$$blocks" = "$$headers" ]; then \
		echo "✓ Sync complete! Blocks: $$blocks"; \
	else \
		echo "⏳ Syncing... Blocks: $$blocks / Headers: $$headers"; \
		progress=$$(dogecoin-cli getblockchaininfo | grep verificationprogress | cut -d: -f2 | tr -d ' ,'); \
		percent=$$(echo "$$progress * 100" | bc -l | cut -d. -f1); \
		echo "Progress: $$percent%"; \
	fi

# -----------------------------------------------------------------------------
# Cleanup Target
# -----------------------------------------------------------------------------

# Remove the virtual environment directories.
clean:
	@echo "Cleaning up: removing $(VENV_DIR)"
	rm -rf $(VENV_DIR)
