#!/usr/bin/env python3
# Full Python script to fetch new tickets from Zammad, extract phone numbers, and update the user's profile.
import requests
import re

# Configuration
ZAMMAD_URL = "https://kontakt.luftglanz.de"
API_TOKEN = "iwXhnY-mb1PFqYHZhtjcRQqgJuNTv0ctPkMthbE2yMG1bXm-NyW2ZkMpu9PX1-9P"  # Replace this with your actual token

HEADERS = {
    "Authorization": f"Token token={API_TOKEN}",
    "Content-Type": "application/json"
}

def get_new_tickets():
    resp = requests.get(f"{ZAMMAD_URL}/api/v1/tickets?state=new", headers=HEADERS)
    resp.raise_for_status()
    return resp.json()

def get_ticket_articles(ticket_id):
    resp = requests.get(f"{ZAMMAD_URL}/api/v1/ticket_articles/by_ticket/{ticket_id}", headers=HEADERS)
    resp.raise_for_status()
    return resp.json()

def extract_phone(text):
    # Look for "Telefonnummer: <number>" or similar
    match = re.search(r'(?:Telefonnummer|Tel\.?|Handy|Mobil)[^\d]*(\+?\d[\d\s\-()]{7,})', text, re.IGNORECASE)
    if match:
        number = match.group(1).replace(" ", "").replace("-", "")
        return number
    # Fallback: generic phone number pattern
    match = re.search(r'(\+?\d[\d\s\-()]{7,})', text)
    if match:
        number = match.group(1).replace(" ", "").replace("-", "")
        return number
    return None

def get_user(user_id):
    resp = requests.get(f"{ZAMMAD_URL}/api/v1/users/{user_id}", headers=HEADERS)
    resp.raise_for_status()
    return resp.json()

def update_user_phone_or_mobile(user_id, phone):
    # If phone starts with 01, treat as mobile
    field = "mobile" if phone.startswith("01") else "phone"
    data = {field: phone}
    resp = requests.put(f"{ZAMMAD_URL}/api/v1/users/{user_id}", json=data, headers=HEADERS)
    return resp.status_code == 200, field

def process():
    tickets = get_new_tickets()
    for ticket in tickets:
        ticket_id = ticket["id"]
        customer_id = ticket["customer_id"]
        articles = get_ticket_articles(ticket_id)

        for article in articles:
            body = article.get("body", "")
            phone = extract_phone(body)

            if phone:
                user = get_user(customer_id)
                # Check if the field is already set
                field = "mobile" if phone.startswith("01") else "phone"
                if not user.get(field):
                    success, used_field = update_user_phone_or_mobile(customer_id, phone)
                    print(f"Updated user {user['email']} with {used_field} {phone}: {'✅' if success else '❌'}")
                break

# Execute the process
process()


