#!/bin/bash
# hot-leads-sync.sh - Sync hot leads from Growth Engine to Notion
# Runs hourly via cron
#
# Cron: 0 * * * * /root/clawd/scripts/hot-leads-sync.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.env"

HOT_LEADS_DB="2f863e0c-a7d5-81db-8677-ffc1dd4c0868"
GROWTH_ENGINE_API="${GROWTH_ENGINE_API:-https://rateright-growth-production.up.railway.app}"

echo "======================================"
echo "  HOT LEADS SYNC"
echo "  $(date)"
echo "======================================"
echo ""

# Fetch hot leads from Growth Engine API (internal endpoint)
echo "Fetching hot leads from Growth Engine..."
LEADS_RESPONSE=$(curl -s -H "X-Internal-Key: $INTERNAL_JOB_KEY" "${GROWTH_ENGINE_API}/api/leads/internal/hot" 2>/dev/null)

# Check if we got valid response
LEAD_COUNT=$(echo "$LEADS_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(len(d.get('leads', d if isinstance(d, list) else [])))" 2>/dev/null || echo "0")

if [ "$LEAD_COUNT" -eq 0 ]; then
    echo "No hot leads found or API error"
    exit 0
fi

echo "Found $LEAD_COUNT hot leads"
echo ""

# Process each lead
echo "$LEADS_RESPONSE" | python3 << 'PYEOF'
import sys
import json
import subprocess
import os
from datetime import datetime, timedelta

NOTION_API_KEY = os.environ.get('NOTION_API_KEY', '')
HOT_LEADS_DB = "2f863e0c-a7d5-81db-8677-ffc1dd4c0868"

data = json.load(sys.stdin)
leads = data.get('leads', data if isinstance(data, list) else [])

def notion_request(method, endpoint, data=None):
    """Make a request to Notion API"""
    import urllib.request
    import urllib.error

    url = f"https://api.notion.com/v1/{endpoint}"
    headers = {
        "Authorization": f"Bearer {NOTION_API_KEY}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28"
    }

    req = urllib.request.Request(url, method=method, headers=headers)
    if data:
        req.data = json.dumps(data).encode('utf-8')

    try:
        with urllib.request.urlopen(req, timeout=10) as response:
            return json.loads(response.read().decode('utf-8'))
    except urllib.error.HTTPError as e:
        return {"error": str(e)}
    except Exception as e:
        return {"error": str(e)}

def find_existing_lead(lead_id):
    """Check if lead already exists in Notion by Lead ID"""
    result = notion_request("POST", f"databases/{HOT_LEADS_DB}/query", {
        "filter": {
            "property": "Lead ID",
            "rich_text": {"equals": str(lead_id)}
        }
    })
    results = result.get('results', [])
    return results[0]['id'] if results else None

def calculate_days_stale(last_contact):
    """Calculate days since last contact"""
    if not last_contact:
        return 999
    try:
        last_date = datetime.fromisoformat(last_contact.replace('Z', '+00:00'))
        now = datetime.now(last_date.tzinfo) if last_date.tzinfo else datetime.now()
        return (now - last_date).days
    except:
        return 999

def sync_lead(lead):
    """Create or update lead in Notion"""
    lead_id = str(lead.get('id', ''))
    first_name = lead.get('first_name', '') or ''
    last_name = lead.get('last_name', '') or ''
    name = f"{first_name} {last_name}".strip() or 'Unknown'
    company = lead.get('company', '') or lead.get('metadata', {}).get('company', '') or ''
    phone = lead.get('phone', '') or ''
    score = lead.get('score', 0) or 0

    # Get last contact from communications or updated_at
    last_contact = lead.get('last_contact') or lead.get('updated_at')
    days_stale = calculate_days_stale(last_contact)

    # Build notes from metadata
    metadata = lead.get('metadata', {})
    notes_parts = []
    if metadata.get('trade'):
        notes_parts.append(f"Trade: {metadata['trade']}")
    if metadata.get('source'):
        notes_parts.append(f"Source: {metadata['source']}")
    if lead.get('status'):
        notes_parts.append(f"Status: {lead['status']}")
    notes = " | ".join(notes_parts)

    # Build properties
    properties = {
        "Name": {"title": [{"text": {"content": name[:100]}}]},
        "Company": {"rich_text": [{"text": {"content": company[:100]}}] if company else []},
        "Phone": {"phone_number": phone if phone else None},
        "Score": {"number": score},
        "Days Stale": {"number": days_stale},
        "Notes": {"rich_text": [{"text": {"content": notes[:500]}}] if notes else []},
        "Lead ID": {"rich_text": [{"text": {"content": lead_id}}]}
    }

    # Add last contact date if valid
    if last_contact:
        try:
            date_str = last_contact[:10]  # YYYY-MM-DD
            properties["Last Contact"] = {"date": {"start": date_str}}
        except:
            pass

    # Check if exists
    existing_id = find_existing_lead(lead_id)

    if existing_id:
        # Update existing
        result = notion_request("PATCH", f"pages/{existing_id}", {"properties": properties})
        action = "Updated"
    else:
        # Create new
        result = notion_request("POST", "pages", {
            "parent": {"database_id": HOT_LEADS_DB},
            "properties": properties
        })
        action = "Created"

    if result.get('error'):
        print(f"  ERROR {name}: {result['error']}")
    else:
        print(f"  {action}: {name} (Score: {score}, Stale: {days_stale}d)")

    return result

# Process leads
print(f"Syncing {len(leads)} leads to Notion...")
print("")

synced = 0
errors = 0

for lead in leads:
    result = sync_lead(lead)
    if result.get('error'):
        errors += 1
    else:
        synced += 1

print("")
print(f"Sync complete: {synced} synced, {errors} errors")
PYEOF

echo ""
echo "======================================"
echo "  HOT LEADS SYNC COMPLETE"
echo "======================================"
