"""
Real Bitcoin mining system with network integration
"""
import os
import sqlite3
import sys

# Add the root directory to Python path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from cpu.db_schema import init_db
from src.core.wallet import BTCWallet
from src.hardware.gpu_manager import GPUManager
from src.server.verification_server import MiningVerificationServer as VerificationServer
from src.mining.real_bitcoin_miner import RealBitcoinMiner
from src.mining.reward_processor import BitcoinRewardProcessor
from bitcoinlib.services.services import Service
import asyncio
import argparse
import traceback

def initialize_database():
    """Initialize the database with required tables"""
    # Initialize database tables using SQLAlchemy
    init_db()

async def main(hf_token: str = None, port: int = 8080, network: str = 'bitcoin'):
    try:
        # Initialize database
        initialize_database()
        
        # Initialize GPU Manager
        gpu_manager = GPUManager()
        print("\nInitialized GPU Manager")
        
        # Create/load Bitcoin wallet
        wallet = BTCWallet(network=network)
        print("\nWallet Info:")
        print(f"Address: {wallet.keys.address}")
        print(f"Network: {network.upper()}")
        
        try:
            # Get real network balance
            network_balance = wallet.get_network_balance()
            print(f"Network Balance: {network_balance} BTC")
        except Exception as e:
            print(f"Warning: Could not fetch network balance: {str(e)}")
            
        # Initialize real Bitcoin miner
        miner = RealBitcoinMiner(
            gpu_manager=gpu_manager,
            wallet_address=wallet.keys.address,
            network=network
        )
        
        # Initialize reward processor
        reward_processor = BitcoinRewardProcessor(network=network)
        
        # Initialize server with real network components
        server = VerificationServer(
            miner=miner,
            reward_processor=reward_processor,
            wallet=wallet,
            host="0.0.0.0",
            port=port
        )
        
    except Exception as e:
        print(f"Error initializing mining system: {str(e)}")
        print("Stack trace:")
        print(traceback.format_exc())
        return
    
    # Start mining in background
    miner.start_mining()
    print("\nMining Started!")
    print("Server starting...")
    
    # Start server
    await server.start()
    print(f"\nServer running at http://localhost:{port}")
    print("\nAvailable endpoints:")
    print(f"- http://localhost:{port}/status      - Mining status")
    print(f"- http://localhost:{port}/wallet      - Wallet details")
    print(f"- http://localhost:{port}/stats       - Mining statistics")
    
    try:
        while True:
            try:
                # Get real network stats
                network_balance = wallet.get_network_balance()
                mining_stats = miner.get_mining_stats()
                reward_stats = reward_processor.get_reward_stats(wallet.keys.address)
                
                print("\nReal Bitcoin Mining Stats:")
                print("-------------------------")
                print(f"Network: {network.upper()}")
                print(f"Network Balance: {network_balance} BTC")
                print(f"Hashrate: {mining_stats['hashrate']/1e6:.2f} MH/s")
                print(f"Blocks Found: {mining_stats['blocks_found']}")
                if mining_stats['last_block']:
                    print(f"Last Block: {mining_stats['last_block']}")
                
                print("\nReward Status:")
                print(f"Pending Rewards: {reward_stats['pending']} BTC")
                print(f"Confirmed Rewards: {reward_stats['confirmed']} BTC")
                print(f"Mature Rewards: {reward_stats['mature']} BTC")
                
                # Still sync to HuggingFace if configured
                if hf_token:
                    wallet.sync_to_cloud()
                    print("Synced to HuggingFace")
                
                await asyncio.sleep(60)
                
            except Exception as e:
                print(f"Error updating stats: {str(e)}")
                await asyncio.sleep(5)
            
    except KeyboardInterrupt:
        print("\nShutting down...")
        miner.stop_mining()
        await server.stop()
        print("Mining stopped. Final stats:")
        stats = wallet.get_mining_stats()
        print(f"Total Mined: {stats['total_mined']}")
        print(f"Final Balance: {stats['current_balance']}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Start real Bitcoin mining server")
    parser.add_argument(
        "--hf-token",
        help="HuggingFace API token for wallet sync"
    )
    parser.add_argument(
        "--port",
        type=int,
        default=8080,
        help="Port to run server on"
    )
    parser.add_argument(
        "--network",
        choices=['bitcoin', 'testnet'],
        default='bitcoin',
        help="Bitcoin network to use (bitcoin or testnet)"
    )
    
    args = parser.parse_args()
    
    # Warn if using mainnet
    if args.network == 'bitcoin':
        print("\nWARNING: You are connecting to the real Bitcoin network!")
        print("Mining difficulty is extremely high. Consider using --network testnet first.")
        if input("Continue with mainnet? (yes/no): ").lower() != 'yes':
            print("Exiting...")
            exit(1)
    
    asyncio.run(main(args.hf_token, args.port, args.network))
