import os
import json
import logging
from urllib.request import Request, urlopen
from urllib.error import URLError
from dotenv import load_dotenv

load_dotenv()
logger = logging.getLogger(__name__)

TELEGRAM_API_URL = "https://api.telegram.org"
BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")


async def send_telegram_message(chat_id: str, text: str) -> dict:
    """Send a message via Telegram Bot API. Returns {success: bool, error: str|null}"""
    if not BOT_TOKEN:
        return {"success": False, "error": "Telegram bot token not configured"}
    
    url = f"{TELEGRAM_API_URL}/bot{BOT_TOKEN}/sendMessage"
    payload = json.dumps({"chat_id": chat_id, "text": text, "parse_mode": "HTML", "disable_web_page_preview": True}).encode("utf-8")
    
    try:
        req = Request(url, data=payload, headers={"Content-Type": "application/json"})
        with urlopen(req, timeout=30) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            if data.get("ok"):
                return {"success": True, "error": None}
            else:
                return {"success": False, "error": data.get("description", "Unknown error")}
    except URLError as e:
        logger.error(f"Telegram send failed: {e}")
        return {"success": False, "error": str(e)}
    except Exception as e:
        logger.error(f"Telegram send failed: {e}")
        return {"success": False, "error": str(e)}


def format_invoice_message(invoice) -> str:
    """Format an invoice as a Telegram message."""
    status_emoji = {"draft": "📝", "issued": "✅", "sent": "📤", "partially_paid": "⏳", "paid": "💰", "overdue": "🔴", "void": "🚫"}
    emoji = status_emoji.get(str(invoice.status) if hasattr(invoice.status, 'value') else invoice.status, "📄")
    return f"""🧾 <b>Invoice {invoice.invoice_number}</b>
━━━━━━━━━━━━━━━
<b>Customer:</b> {getattr(invoice.customer, 'name', 'N/A')}
<b>Amount:</b> {invoice.currency} {float(invoice.total_amount):,.2f}
<b>Status:</b> {emoji} {str(invoice.status).upper() if hasattr(invoice.status, 'value') else invoice.status.upper()}
<b>Due Date:</b> {invoice.due_date or 'Upon receipt'}"""


def format_reminder_message(reminder_type: str, entity_name: str, days_remaining: int, details: str = "") -> str:
    """Format a reminder notification as Telegram message."""
    if reminder_type == "subscription_expiry":
        return f"""⏰ <b>Subscription Expiry Reminder</b>
━━━━━━━━━━━━━━━
<b>Subscription:</b> {entity_name}
<b>Expires in:</b> {days_remaining} days
{details}"""
    elif reminder_type == "invoice_overdue":
        return f"""🔴 <b>Invoice Overdue</b>
━━━━━━━━━━━━━━━
<b>Invoice:</b> {entity_name}
<b>Days overdue:</b> {days_remaining}
{details}"""
    else:
        return f"""📌 <b>Reminder</b>
━━━━━━━━━━━━━━━
<b>Item:</b> {entity_name}
{details}"""