#!/usr/bin/env python3
"""
LuckySt Syndicate - Cancel Scheduled Game on Base

Sends an on-chain cancellation transaction to Base, referencing
the original schedule TX. Viewable on BaseScan.

Usage:
    export LUCKYST_NETWORK=testnet
    export LUCKBOT_BASE_PRIVATE_KEY=ff0fbd2c...
    export LUCKBOT_BASE_ADDRESS=0x98F18D8F...

    python -m agentic.syndicate.hackathon_cancel
"""

import os
import sys
import json
import asyncio
from datetime import datetime, timezone

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))

os.environ.setdefault("LUCKYST_NETWORK", "testnet")

from agentic.syndicate.chain_writer import (
    write_report_to_chain,
    BASE_CHAIN_ID,
    BASE_RPC_URL,
)
from agentic.syndicate.pledge import NETWORK

BASE_ADDRESS = os.environ.get("LUCKBOT_BASE_ADDRESS", "")
BASE_PRIVATE_KEY = os.environ.get("LUCKBOT_BASE_PRIVATE_KEY", "")

EXPLORER_BASE = (
    "https://sepolia.basescan.org" if NETWORK == "testnet"
    else "https://basescan.org"
)

STATE_FILE = os.path.join(os.path.dirname(__file__), ".hackathon_state.json")


async def main():
    print("""
    ██╗     ██╗   ██╗ ██████╗██╗  ██╗██╗   ██╗███████╗████████╗
    ██║     ██║   ██║██╔════╝██║ ██╔╝╚██╗ ██╔╝██╔════╝╚══██╔══╝
    ██║     ██║   ██║██║     █████╔╝  ╚████╔╝ ███████╗   ██║
    ██║     ██║   ██║██║     ██╔═██╗   ╚██╔╝  ╚════██║   ██║
    ███████╗╚██████╔╝╚██████╗██║  ██╗   ██║   ███████║   ██║
    ╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝   ╚═╝   ╚══════╝   ╚═╝

         C A N C E L   S C H E D U L E D   G A M E
    """)

    if not BASE_ADDRESS or not BASE_PRIVATE_KEY:
        print("ERROR: Set LUCKBOT_BASE_ADDRESS and LUCKBOT_BASE_PRIVATE_KEY")
        sys.exit(1)

    # Load state from deploy
    if not os.path.exists(STATE_FILE):
        print("ERROR: No deploy state found. Run hackathon_deploy first.")
        sys.exit(1)

    with open(STATE_FILE) as f:
        state = json.load(f)

    schedule_tx = state.get("schedule_tx")
    games = state.get("games", [])

    print(f"  Agent:       {state.get('agent_id')}")
    print(f"  Network:     {NETWORK} (chain {BASE_CHAIN_ID})")
    print(f"  Schedule TX: {schedule_tx}")
    for game in games:
        print(f"  Markets:     {', '.join(game.get('markets', []))}")

    # Build cancellation payload
    cancel_data = {
        "type": "schedule_cancel",
        "version": 1,
        "agent_id": state.get("agent_id"),
        "base_address": BASE_ADDRESS,
        "chain_id": BASE_CHAIN_ID,
        "original_schedule_tx": schedule_tx,
        "reason": "Cancelled by operator — hackathon demo",
        "cancelled_at": datetime.now(timezone.utc).isoformat(),
        "games_cancelled": [g.get("markets") for g in games],
    }

    # Prefix byte 0x03 = cancellation
    payload_bytes = b"\x03" + json.dumps(cancel_data).encode("utf-8")

    print("\n  Broadcasting cancellation to Base...")
    result = await write_report_to_chain(
        payload_bytes, BASE_PRIVATE_KEY, BASE_ADDRESS
    )

    if result.success and result.tx_hash:
        print(f"\n  Cancel TX:  {result.tx_hash}")
        print(f"  Block:      {result.block_number}")
        print(f"  Gas:        {result.gas_used}")
        print(f"  Explorer:   {EXPLORER_BASE}/tx/{result.tx_hash}")

        # Update state
        state["cancel_tx"] = result.tx_hash
        state["cancelled_at"] = datetime.now(timezone.utc).isoformat()
        with open(STATE_FILE, "w") as f:
            json.dump(state, f, indent=2)

        print("\n  SCHEDULE CANCELLED")
        print("  All 3 transactions visible on BaseScan:")
        if state.get("pledge_tx"):
            print(f"    1. Pledge:  {EXPLORER_BASE}/tx/{state['pledge_tx']}")
        print(f"    2. Schedule: {EXPLORER_BASE}/tx/{schedule_tx}")
        print(f"    3. Cancel:   {EXPLORER_BASE}/tx/{result.tx_hash}")
    else:
        print(f"\n  CANCEL FAILED: {result.error}")

    print()


if __name__ == "__main__":
    asyncio.run(main())
