#!/usr/bin/env python3
"""
Philips LatteGo 5500 Series Price Check
Searches idealo.de and geizhals.de for 7 models, builds markdown table, sends via Telegram.
Runs as no_agent cron job - deterministic, fast, free.
"""
import re
import json
import subprocess
import sys
from datetime import datetime
from urllib.parse import quote_plus

import requests
from bs4 import BeautifulSoup

# ─── Model Config ──────────────────────────────────────────────────────────
MODELS = [
    {"id": "EP5547/90", "color": "Schwarz/Chrom",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/204400188_-series-5500-latte-go-ep5541-50-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5547-90-series-5500-a3154454.html",
     "philips_url": "https://www.philips.de/c-p/EP5547_90/-"},
    {"id": "EP5544/80", "color": "Grau",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/204400170_-series-5500-latte-go-kaffeevollautomat-ep5543-80-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5544-80-series-5500-a3175794.html",
     "philips_url": "https://www.philips.de/c-p/EP5544_80/-"},
    {"id": "EP5543/80", "color": "Rosé-Weiß",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/204400170_-series-5500-latte-go-kaffeevollautomat-ep5543-80-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5543-80-series-5500-a3175803.html",
     "philips_url": "https://www.philips.de/c-p/EP5543_80/-"},
    {"id": "EP5543/90", "color": "Chrom-Weiß",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/204451742_-series-5500-latte-go-kaffeevollautomat-ep5543-90-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5543-90-series-5500-a3213917.html",
     "philips_url": "https://www.philips.de/c-p/EP5543_90/series-5500-kaffeevollautomat"},
    {"id": "EP5541/50", "color": "Schwarz",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/204400188_-series-5500-latte-go-ep5541-50-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5541-50-series-5500-a3253201.html",
     "philips_url": "https://www.philips.de/c-p/EP5541_50/-"},
    {"id": "EP5545/70", "color": "Weiß",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/206340682_-series-5500-latte-go-ep5545-70-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5545-70-series-5500-a3175778.html",
     "philips_url": "https://www.philips.de/c-p/EP5545_70/-"},
    {"id": "EP5549/70", "color": "Schwarz/Silber",
     "idealo_url": "https://www.idealo.de/preisvergleich/OffersOfProduct/204451452_-series-5500-latte-go-kaffeevollautomat-ep5549-70-schwarz-silber-philips.html",
     "geizhals_url": "https://geizhals.de/philips-ep5549-70-series-5500-a3229000.html",
     "philips_url": "https://www.philips.de/c-p/EP5549_70/-"},
]

HEADERS = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept-Language": "de-DE,de;q=0.9,en;q=0.8",
}

SESSION = requests.Session()
SESSION.headers.update(HEADERS)


# ─── Helpers ───────────────────────────────────────────────────────────────
def fetch(url: str, timeout: int = 15) -> str | None:
    try:
        r = SESSION.get(url, timeout=timeout)
        r.raise_for_status()
        return r.text
    except Exception as e:
        print(f"[WARN] Fetch failed {url}: {e}", file=sys.stderr)
        return None


def extract_idealo_total_price(html: str) -> float | None:
    """Find 'Günstigster Gesamtpreis' or 'Günstigster Gesamtpreis inkl. Versand' in idealo HTML."""
    # Pattern: 503,95 € inkl. Versand  or  503,95 €
    patterns = [
        r'Günstigster Gesamtpreis[^€]*€\s*([\d.,]+)\s*€?\s*inkl\.?\s*Versand',
        r'Günstigster Gesamtpreis[^€]*([\d.,]+)\s*€',
        r'gesamtpreis[^€]*([\d.,]+)\s*€',
    ]
    for pat in patterns:
        m = re.search(pat, html, re.IGNORECASE)
        if m:
            val = m.group(1).replace(".", "").replace(",", ".")
            try:
                return float(val)
            except ValueError:
                pass
    return None


def extract_geizhals_price(html: str) -> float | None:
    """Find price with GRATISVERSAND badge on Geizhals."""
    soup = BeautifulSoup(html, "html.parser")
    # Look for offer rows with GRATISVERSAND
    for offer in soup.select(".offer, .gh_offer, [class*='offer']"):
        text = offer.get_text(" ", strip=True)
        if "GRATISVERSAND" in text.upper() or "GRATIS VERSAND" in text.upper():
            # Extract first price-like number
            m = re.search(r'(\d{1,3}(?:\.\d{3})*(?:,\d{2})?)\s*€', text)
            if m:
                val = m.group(1).replace(".", "").replace(",", ".")
                try:
                    return float(val)
                except ValueError:
                    pass
    # Fallback: any price on page
    m = re.search(r'€\s*(\d{1,3}(?:\.\d{3})*(?:,\d{2})?)', html)
    if m:
        val = m.group(1).replace(".", "").replace(",", ".")
        try:
            return float(val)
        except ValueError:
            pass
    return None


def extract_philips_price(html: str) -> float | None:
    """Philips direct shop - price shown is final (free shipping >40€)."""
    # Look for price pattern like "499,99 €"
    patterns = [
        r'(\d{1,3}(?:\.\d{3})*(?:,\d{2})?)\s*€',
        r'Preis[^€]*(\d{1,3}(?:\.\d{3})*(?:,\d{2})?)\s*€',
    ]
    for pat in patterns:
        m = re.search(pat, html)
        if m:
            val = m.group(1).replace(".", "").replace(",", ".")
            try:
                return float(val)
            except ValueError:
                pass
    return None


def get_price(model: dict) -> tuple[float | None, str]:
    """Try all three sources, return (price, source_name)."""
    # 1. Geizhals (often cheapest with free shipping)
    html = fetch(model["geizhals_url"])
    if html:
        price = extract_geizhals_price(html)
        if price:
            return price, "Geizhals"

    # 2. idealo
    html = fetch(model["idealo_url"])
    if html:
        price = extract_idealo_total_price(html)
        if price:
            return price, "idealo"

    # 3. Philips Direct
    html = fetch(model["philips_url"])
    if html:
        price = extract_philips_price(html)
        if price:
            return price, "Philips Direct"

    return None, "–"


def build_table(results: list[dict]) -> str:
    """Build markdown table from results."""
    now = datetime.now().strftime("%d.%m.%Y, %H:%M Uhr")
    lines = [f"**Preise vom {now}**", ""]
    lines.append("| Modell | Farbe | Preis (inkl. Versand) | Quelle | Link |")
    lines.append("|--------|-------|----------------------|--------|------|")

    # Sort by price ascending
    results.sort(key=lambda x: x["price"] if x["price"] else 9999)

    warnings = []
    for r in results:
        if r["price"] is None:
            warnings.append(f"⚠ {r['model']}: Preis nicht gefunden")
            continue
        price_str = f"{r['price']:,.2f} €".replace(",", "X").replace(".", ",").replace("X", ".")
        link_text = r["source"].split()[0].lower() + ".de"
        link_url = r["source_url"]
        lines.append(f"| {r['model']} | {r['color']} | {price_str} | {r['source']} | [{link_text}]({link_url}) |")

    table = "\n".join(lines)

    # Summary line
    cheapest = next((r for r in results if r["price"] is not None), None)
    if cheapest:
        price_str = f"{cheapest['price']:,.2f} €".replace(",", "X").replace(".", ",").replace("X", ".")
        summary = f"\nGünstigstes Modell: {cheapest['model']} für {price_str} ({cheapest['source']})"
    else:
        summary = "\nKeine Preise gefunden."

    if warnings:
        summary += "\n" + "\n".join(warnings)

    return table + summary


def send_telegram(text: str) -> bool:
    """Send via hermes send CLI."""
    try:
        env = {"HERMES_HOME": "/opt/data"}
        result = subprocess.run(
            ["/opt/hermes/bin/hermes", "send", "--to", "telegram", text],
            env={**os.environ, **env},
            capture_output=True,
            text=True,
            timeout=30,
        )
        if result.returncode == 0:
            print(f"[OK] Telegram sent: {result.stdout.strip()}")
            return True
        else:
            print(f"[ERR] Telegram failed: {result.stderr}", file=sys.stderr)
            return False
    except Exception as e:
        print(f"[ERR] Telegram exception: {e}", file=sys.stderr)
        return False


# ─── Main ──────────────────────────────────────────────────────────────────
if __name__ == "__main__":
    import os

    print("[INFO] Starting Philips 5500 price check...")
    results = []

    for model in MODELS:
        print(f"[INFO] Checking {model['id']} ({model['color']})...")
        price, source = get_price(model)
        results.append({
            "model": model["id"],
            "color": model["color"],
            "price": price,
            "source": source,
            "source_url": model["geizhals_url"] if source == "Geizhals"
                          else model["idealo_url"] if source == "idealo"
                          else model["philips_url"],
        })
        if price:
            print(f"  -> {price:.2f} € ({source})")
        else:
            print(f"  -> NOT FOUND")

    table_md = build_table(results)
    print("[INFO] Table built, sending to Telegram...")
    send_telegram(table_md)
    print("[INFO] Done.")