"""
Deploy AgreementRegistry.sol to Polygon Amoy testnet using web3.py + native solc.
Run from project root: python3 contracts/deploy.py
"""
import sys, os, subprocess, json
sys.path.insert(0, 'backend')

from dotenv import load_dotenv
load_dotenv('.env')

from web3 import Web3

# ── Config ───────────────────────────────────────────────────────────────────
RPC_URL     = os.getenv("POLYGON_RPC_URL", "https://rpc-amoy.polygon.technology/")
PRIVATE_KEY = os.getenv("POLYGON_PRIVATE_KEY", "")
CHAIN_ID    = 80002

w3      = Web3(Web3.HTTPProvider(RPC_URL))
account = w3.eth.account.from_key(PRIVATE_KEY)

print(f"Connected : {w3.is_connected()}")
print(f"Address   : {account.address}")
print(f"Balance   : {w3.from_wei(w3.eth.get_balance(account.address), 'ether')} POL")
print(f"Chain ID  : {w3.eth.chain_id}")

# ── Compile with native solc (installed via Homebrew) ────────────────────────
sol_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "AgreementRegistry.sol")
print(f"\nCompiling {sol_path} ...")

result = subprocess.run(
    ["solc", "--combined-json", "abi,bin", "--optimize", sol_path],
    capture_output=True, text=True
)
if result.returncode != 0:
    print(f"❌ Compilation failed:\n{result.stderr}")
    sys.exit(1)

compiled   = json.loads(result.stdout)
key        = list(compiled["contracts"].keys())[0]   # e.g. "path:AgreementRegistry"
raw_abi    = compiled["contracts"][key]["abi"]
abi        = json.loads(raw_abi) if isinstance(raw_abi, str) else raw_abi
bytecode   = compiled["contracts"][key]["bin"]
print(f"✅ Compiled successfully  (contract key: {key})")

# ── Deploy ───────────────────────────────────────────────────────────────────
ContractFactory = w3.eth.contract(abi=abi, bytecode=bytecode)

gas_price = w3.eth.gas_price
tip        = w3.to_wei(35, "gwei")
max_fee    = gas_price + tip

print(f"\nDeploying ... (base gas: {w3.from_wei(gas_price, 'gwei'):.1f} gwei, tip: 35 gwei)")

tx = ContractFactory.constructor().build_transaction({
    "from":                 account.address,
    "nonce":                w3.eth.get_transaction_count(account.address),
    "gas":                  800_000,
    "maxFeePerGas":         max_fee,
    "maxPriorityFeePerGas": tip,
    "chainId":              CHAIN_ID,
})

signed  = w3.eth.account.sign_transaction(tx, PRIVATE_KEY)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
print(f"Tx sent   : 0x{tx_hash.hex()}")
print("Waiting for confirmation (~2 seconds) ...")

receipt          = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120)
contract_address = receipt.contractAddress

print(f"\n{'='*60}")
print(f"✅ CONTRACT DEPLOYED SUCCESSFULLY")
print(f"{'='*60}")
print(f"Contract Address : {contract_address}")
print(f"Transaction Hash : 0x{tx_hash.hex()}")
print(f"Block Number     : {receipt.blockNumber}")
print(f"Gas Used         : {receipt.gasUsed}")
print(f"Explorer         : https://amoy.polygonscan.com/address/{contract_address}")
print(f"{'='*60}")
print(f"\n📋 Add this to your .env:")
print(f"AGREEMENT_CONTRACT_ADDRESS={contract_address}")
