import os
import json
from dotenv import load_dotenv
from web3 import Web3
from web3.exceptions import Web3Exception

# ✅ Load environment variables
USER_PROJECT_DIR = os.getcwd()
USER_ENV_PATH = os.path.join(USER_PROJECT_DIR, ".env")

if os.path.exists(USER_ENV_PATH):
    load_dotenv(USER_ENV_PATH)
else:
    print("⚠️ Warning: No `.env` file found in your project directory! Transactions requiring signing may fail.")

# ✅ Load keys from the environment
PRIVATE_KEY = os.getenv("PRIVATE_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

if not PRIVATE_KEY:
    print("⚠️ Warning: PRIVATE_KEY not set. Please create a `.env` file in your project with your keys.")
    PRIVATE_KEY = None  # Allow package to be installed but prevent transactions

# ✅ Define RPC URL and initialize Web3
RPC_URL = "https://rpc.test.mezo.org"
web3_instance = Web3(Web3.HTTPProvider(RPC_URL))

if not web3_instance.is_connected():
    raise ConnectionError("❌ Failed to connect to Mezo Matsnet RPC.")

# ✅ Initialize account and sender address
if PRIVATE_KEY:
    account = web3_instance.eth.account.from_key(PRIVATE_KEY)
    sender_address = account.address
else:
    account = None
    sender_address = None

# ✅ Set up contract details (for mUSD)
MUSD_ADDRESS = "0x637e22A1EBbca50EA2d34027c238317fD10003eB"
ERC20_ABI = json.loads(
    '[{"constant": false, "inputs": [{"name": "recipient", "type": "address"},'
    '{"name": "amount", "type": "uint256"}],"name": "transfer","outputs": [{"name": "", "type": "bool"}],'
    '"stateMutability": "nonpayable","type":"function"}]'
)
musd_contract = web3_instance.eth.contract(address=MUSD_ADDRESS, abi=ERC20_ABI)