#!/usr/bin/env python3
"""
URL Scheme Integration for Apple Shortcuts
Creates URL schemes that Shortcuts can use to communicate with OpenClaw
"""
import argparse
import urllib.parse
import json
from pathlib import Path

BASE_URL = "https://t.me/clawdbot"

def create_url_scheme(action, **params):
    """Create a URL scheme for OpenClaw"""
    
    # Build the start parameter
    param_str = "_".join([f"{k}:{v}" for k, v in params.items()])
    start_param = f"{action}_{param_str}"
    
    # URL encode
    encoded = urllib.parse.quote(start_param, safe='')
    
    return f"{BASE_URL}?start={encoded}"

def create_shortcut_url(name, input_type="text", input_value=""):
    """Create a shortcuts:// URL to run a shortcut"""
    encoded_name = urllib.parse.quote(name, safe='')
    url = f"shortcuts://run-shortcut?name={encoded_name}"
    
    if input_type and input_value:
        encoded_input = urllib.parse.quote(input_value, safe='')
        url += f"&input={input_type}&text={encoded_input}"
    
    return url

def generate_n8n_webhook_url(webhook_id, data=None):
    """Generate n8n webhook URL"""
    base = f"https://n8n.kangaroo-eel.ts.net/webhook/{webhook_id}"
    if data:
        params = urllib.parse.urlencode(data)
        return f"{base}?{params}"
    return base

def create_send_to_openclaw_url(message):
    """Create URL to send message to OpenClaw via Telegram"""
    return create_url_scheme("msg", text=message[:100])  # Limit length

def create_home_assistant_url(entity_id, action="turn_on"):
    """Create Home Assistant webhook URL"""
    return f"http://homeassistant.kangaroo-eel.ts.net:8123/api/webhook/{entity_id}_{action}"

def list_integrations():
    """List available URL scheme integrations"""
    integrations = {
        "send-telegram": {
            "description": "Send text to OpenClaw via Telegram",
            "url": "https://t.me/clawdbot?start=msg_<text>",
            "example": "python3 url-scheme.py --action send-telegram --message 'Hello'"
        },
        "trigger-morning-briefing": {
            "description": "Manually trigger Morning Intelligence Briefing",
            "url": "https://t.me/clawdbot?start=morning_briefing_now",
            "example": "python3 url-scheme.py --action trigger-morning-briefing"
        },
        "log-expense": {
            "description": "Quick expense log",
            "url": "https://t.me/clawdbot?start=expense_<amount>_<category>",
            "example": "python3 url-scheme.py --action log-expense --amount 25.50 --category Food"
        },
        "add-task": {
            "description": "Add task to Notion",
            "url": "https://t.me/clawdbot?start=task_<name>_<priority>",
            "example": "python3 url-scheme.py --action add-task --task 'Buy milk' --priority High"
        },
        "trigger-n8n": {
            "description": "Trigger n8n workflow",
            "url": "https://n8n.kangaroo-eel.ts.net/webhook/<webhook-id>",
            "example": "python3 url-scheme.py --action trigger-n8n --webhook my-workflow"
        }
    }
    
    print("🔗 Available URL Scheme Integrations:")
    print("=" * 60)
    for key, info in integrations.items():
        print(f"\n🔹 {key}")
        print(f"   {info['description']}")
        print(f"   URL: {info['url']}")
        print(f"   Usage: {info['example']}")

def generate_qr_code(url, output_file=None):
    """Generate QR code for URL (requires qrcode package)"""
    try:
        import qrcode
        qr = qrcode.QRCode(version=1, box_size=10, border=5)
        qr.add_data(url)
        qr.make(fit=True)
        
        img = qr.make_image(fill_color="black", back_color="white")
        
        if output_file:
            img.save(output_file)
            print(f"📱 QR Code saved: {output_file}")
        else:
            print(f"📱 QR Code generated for: {url}")
            print("   (Install 'qrcode' and 'pillow' packages to save as image)")
            
    except ImportError:
        print(f"📱 URL: {url}")
        print("   (Install 'qrcode' package to generate QR codes)")

def main():
    parser = argparse.ArgumentParser(description="URL Scheme Integration for Apple Shortcuts")
    parser.add_argument("--action", "-a", help="Action type")
    parser.add_argument("--message", "-m", help="Message text")
    parser.add_argument("--amount", help="Expense amount")
    parser.add_argument("--category", help="Expense category")
    parser.add_argument("--task", help="Task name")
    parser.add_argument("--priority", default="Medium", help="Task priority")
    parser.add_argument("--webhook", help="n8n webhook ID")
    parser.add_argument("--list", "-l", action="store_true", help="List available integrations")
    parser.add_argument("--qr", "-q", action="store_true", help="Generate QR code")
    parser.add_argument("--output", "-o", help="Output file for QR code")
    
    args = parser.parse_args()
    
    if args.list:
        list_integrations()
        return
    
    url = None
    
    if args.action == "send-telegram":
        if not args.message:
            print("❌ --message required for send-telegram")
            return
        url = create_send_to_openclaw_url(args.message)
        print(f"📱 URL Scheme created:")
        print(f"   {url}")
        print(f"\n   Use in Shortcuts with 'Open URL' action")
        
    elif args.action == "trigger-morning-briefing":
        url = f"{BASE_URL}?start=morning_briefing_now"
        print(f"📱 Morning Briefing trigger:")
        print(f"   {url}")
        
    elif args.action == "log-expense":
        if not args.amount or not args.category:
            print("❌ --amount and --category required for log-expense")
            return
        url = create_url_scheme("expense", amount=args.amount, category=args.category)
        print(f"📱 Expense logger URL:")
        print(f"   {url}")
        
    elif args.action == "add-task":
        if not args.task:
            print("❌ --task required for add-task")
            return
        url = create_url_scheme("task", name=args.task.replace(" ", "_"), priority=args.priority)
        print(f"📱 Task adder URL:")
        print(f"   {url}")
        
    elif args.action == "trigger-n8n":
        if not args.webhook:
            print("❌ --webhook required for trigger-n8n")
            return
        url = generate_n8n_webhook_url(args.webhook)
        print(f"📱 n8n Webhook URL:")
        print(f"   {url}")
        
    elif args.action == "run-shortcut":
        if not args.message:
            print("❌ --message (shortcut name) required")
            return
        url = create_shortcut_url(args.message)
        print(f"📱 Run Shortcut URL:")
        print(f"   {url}")
    
    else:
        print("❌ Unknown action. Use --list to see available options.")
        list_integrations()
        return
    
    # Generate QR code if requested
    if args.qr and url:
        generate_qr_code(url, args.output)
    
    # Copy to clipboard hint
    print(f"\n💡 Tip: This URL can be used in Shortcuts 'Open URLs' action")

if __name__ == "__main__":
    main()
