#!/usr/bin/env python3
"""
Test script to check position state on-chain
"""
import sys
import os
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent))

from apollox_v2_client import ApolloXV2Client
import json
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Read wallet private key from .env
private_key = os.getenv('WALLET_PRIVATE_KEY')
if not private_key:
    raise ValueError("WALLET_PRIVATE_KEY not found in .env")

# Read positions
with open('positions.json', 'r') as f:
    positions_data = json.load(f)

print("="*80)
print("🔍 TEST POSITION STATE ON-CHAIN")
print("="*80)

# Initialize client
client = ApolloXV2Client(private_key=private_key)

print(f"\n✅ Client initialized")
print(f"   Wallet: {client.account.address}")
print(f"   Chain: BSC (56)")

# Check each position
if 'positions' in positions_data:
    for trade_hash, pos in positions_data['positions'].items():
        if pos.get('status') == 'OPEN':
            symbol = pos.get('symbol')

            print(f"\n{'='*80}")
            print(f"📊 Checking position: {symbol}")
            print(f"   Local trade_hash: {trade_hash}")
            print(f"   Local entry: ${pos.get('entry_price', 0):.2f}")
            print(f"   Local leverage: {pos.get('leverage', 0)}x")
            print(f"   Local margin: ${pos.get('margin', 0):.2f}")
            print(f"{'='*80}")

            # Query on-chain state
            state = client.get_position_state(trade_hash)

            if state:
                print(f"\n✅ Position EXISTS on-chain")

                # Compare with local
                if state['user'].lower() == client.account.address.lower():
                    print(f"✅ Ownership: CORRECT (matches our wallet)")
                else:
                    print(f"❌ Ownership: WRONG!")
                    print(f"   On-chain owner: {state['user']}")
                    print(f"   Our wallet: {client.account.address}")
            else:
                print(f"\n❌ Position does NOT exist on-chain!")
                print(f"   Possible reasons:")
                print(f"   1. Already closed")
                print(f"   2. Liquidated")
                print(f"   3. Trade hash mismatch")
else:
    print("\n⚠️  No positions found in positions.json")

print("\n" + "="*80)
print("✅ Test complete")
print("="*80)
