#!/usr/bin/env python3
"""
Altria VICIdial → CRM Integration
Transcribes call recordings with local Whisper, then classifies using
VICIdial disposition codes + keyword analysis (no external AI API needed).
"""
import os, sys, json, subprocess, tempfile, sqlite3, logging, urllib.request, ssl, re
from datetime import datetime

ENV_FILE = '/opt/altria/.env'
def _load_env():
    if not os.path.exists(ENV_FILE): return
    for line in open(ENV_FILE):
        line = line.strip()
        if line and not line.startswith('#') and '=' in line:
            k, v = line.split('=', 1)
            os.environ.setdefault(k.strip(), v.strip())
_load_env()

CRM_WEBHOOK_URL    = os.environ.get('CRM_WEBHOOK_URL', '')
CRM_WEBHOOK_SECRET = os.environ.get('CRM_WEBHOOK_SECRET', '')
DB_HOST            = os.environ.get('DB_HOST', 'localhost')
DB_USER            = os.environ.get('DB_USER', 'cron')
DB_PASS            = os.environ.get('DB_PASS', '1234')
DB_NAME            = os.environ.get('DB_NAME', 'asterisk')
DB_PORT            = int(os.environ.get('DB_PORT', '3306'))
WHISPER_BIN        = os.environ.get('WHISPER_BIN', '/opt/whisper.cpp/build/bin/whisper-cli')
WHISPER_MODEL      = os.environ.get('WHISPER_MODEL', '/opt/whisper.cpp/models/ggml-small.en.bin')
MIN_CALL_LENGTH    = int(os.environ.get('MIN_CALL_LENGTH', '30'))

# ─── State DB ─────────────────────────────────────────────────────────────────
STATE_DB = '/opt/altria/state.db'
def _init_state():
    conn = sqlite3.connect(STATE_DB)
    conn.execute('CREATE TABLE IF NOT EXISTS processed (recording_id INTEGER PRIMARY KEY, processed_at TEXT, result TEXT)')
    conn.commit()
    return conn
def _is_processed(conn, rid):
    return conn.execute('SELECT 1 FROM processed WHERE recording_id=?', (rid,)).fetchone() is not None
def _mark_processed(conn, rid, result):
    conn.execute('INSERT OR REPLACE INTO processed VALUES (?,?,?)', (rid, datetime.utcnow().isoformat(), result))
    conn.commit()

# ─── Logging ──────────────────────────────────────────────────────────────────
os.makedirs('/opt/altria/logs', exist_ok=True)
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s',
    handlers=[
        logging.FileHandler('/opt/altria/logs/triage.log'),
        logging.StreamHandler(sys.stdout),
    ])
log = logging.getLogger(__name__)

# ─── Classification engine (no external API) ──────────────────────────────────
# VICIdial disposition codes that always trigger an ALERT
ALERT_DISPOSITIONS = {
    'ESCALATE', 'ESCL', 'XFER', 'XESCL',
    'COMPLAINT', 'LEGAL', 'ABUSE', 'THREAT',
}

# Disposition → ticket category + priority
DISPOSITION_MAP = {
    'SALE':       ('sale',       'low'),
    'CALLBK':     ('callback',   'medium'),
    'REFUND':     ('billing',    'high'),
    'PROMOTE':    ('general',    'low'),
    'RESOLUTION': ('general',    'medium'),
    'ACCEPT':     ('general',    'low'),
    'NI':         ('general',    'low'),      # Not Interested
    'NA':         ('general',    'low'),      # No Answer
    'B':          ('general',    'low'),      # Busy
    'DC':         ('general',    'low'),      # Disconnected
    'YPVM':       ('general',    'low'),      # Voicemail
    'VM':         ('general',    'low'),
    'A':          ('general',    'low'),      # Answering machine
}

# Keywords that escalate a call to ALERT regardless of disposition
ALERT_KEYWORDS = [
    'supervisor', 'manager', 'lawsuit', 'lawyer', 'attorney',
    'sue', 'court', 'legal action', 'police', 'threaten',
    'harassment', 'harassing', 'inappropriate', 'offensive',
    'racist', 'discrimination', 'fbi', 'report you',
]

# Keywords by category (checked in order)
CATEGORY_KEYWORDS = {
    'billing':   ['refund', 'charge', 'bill', 'invoice', 'payment', 'credit card', 'overcharged', 'price'],
    'technical': ['not working', "doesn't work", 'broken', 'error', 'bug', 'crash', 'slow', 'outage'],
    'complaint': ['unhappy', 'disappointed', 'terrible', 'awful', 'worst', 'horrible', 'unacceptable', 'ridiculous'],
    'escalation':['escalate', 'supervisor', 'manager', 'not acceptable', 'this is unacceptable'],
}

# Words that indicate negative/hostile sentiment
HOSTILE_WORDS   = ['angry', 'furious', 'outraged', 'livid', 'disgusting', 'idiot', 'stupid', 'useless', 'incompetent']
NEGATIVE_WORDS  = ['frustrated', 'annoyed', 'upset', 'unhappy', 'disappointed', 'terrible', 'horrible', 'awful', 'bad service']
POSITIVE_WORDS  = ['thank you', 'great', 'excellent', 'wonderful', 'happy', 'satisfied', 'appreciate', 'helpful']


def classify(transcript, disposition, length_sec):
    """
    Classify a call using VICIdial disposition + transcript keywords.
    Returns dict: action, priority, sentiment, category, summary, alert_message
    """
    tx_lower = (transcript or '').lower()
    disp_upper = (disposition or '').upper().strip()

    # ── 1. Disposition-based alert ─────────────────────────────────────────────
    if disp_upper in ALERT_DISPOSITIONS:
        return {
            'action':        'alert',
            'priority':      'urgent',
            'sentiment':     'hostile',
            'category':      'escalation',
            'summary':       'Agent marked call as {}.'.format(disp_upper),
            'alert_message': 'Call disposition {} requires immediate supervisor attention.'.format(disp_upper),
        }

    # ── 2. Transcript keyword alert ────────────────────────────────────────────
    triggered = [kw for kw in ALERT_KEYWORDS if kw in tx_lower]
    if triggered:
        return {
            'action':        'alert',
            'priority':      'urgent',
            'sentiment':     'hostile',
            'category':      'escalation',
            'summary':       'Call contains escalation keywords: {}.'.format(', '.join(triggered[:3])),
            'alert_message': 'Caller used escalation language: "{}". Review immediately.'.format(triggered[0]),
        }

    # ── 3. Category detection ──────────────────────────────────────────────────
    category = 'general'
    for cat, words in CATEGORY_KEYWORDS.items():
        if any(w in tx_lower for w in words):
            category = cat
            break

    # Override category with disposition mapping
    disp_category, disp_priority = DISPOSITION_MAP.get(disp_upper, ('general', 'low'))
    if category == 'general':
        category = disp_category

    # ── 4. Priority ────────────────────────────────────────────────────────────
    priority = disp_priority
    if category == 'complaint':
        priority = 'high'
    elif category == 'billing' and any(w in tx_lower for w in ['overcharged', 'wrong charge', 'dispute']):
        priority = 'high'
    elif category == 'technical' and any(w in tx_lower for w in ['outage', 'down', 'urgent', 'emergency']):
        priority = 'high'
    # Long calls usually indicate a difficult interaction
    if length_sec > 600 and priority == 'low':
        priority = 'medium'

    # ── 5. Sentiment ───────────────────────────────────────────────────────────
    if any(w in tx_lower for w in HOSTILE_WORDS):
        sentiment = 'hostile'
        if priority == 'low': priority = 'high'
    elif any(w in tx_lower for w in NEGATIVE_WORDS):
        sentiment = 'negative'
        if priority == 'low': priority = 'medium'
    elif any(w in tx_lower for w in POSITIVE_WORDS):
        sentiment = 'positive'
    else:
        sentiment = 'neutral'

    # ── 6. Summary ─────────────────────────────────────────────────────────────
    first_line = transcript.strip().split('\n')[0][:120] if transcript else ''
    summary = 'Disposition: {}. {}{}s call. {}'.format(
        disp_upper or 'Unknown',
        'Long ' if length_sec > 300 else '',
        length_sec,
        first_line,
    )

    return {
        'action':        'ticket',
        'priority':      priority,
        'sentiment':     sentiment,
        'category':      category,
        'summary':       summary,
        'alert_message': None,
    }


# ─── DB ───────────────────────────────────────────────────────────────────────
def get_new_recordings():
    try:
        import mysql.connector
    except ImportError:
        log.error("Run: pip3 install mysql-connector-python"); return []
    conn = mysql.connector.connect(host=DB_HOST, user=DB_USER, password=DB_PASS, database=DB_NAME, port=DB_PORT)
    cur = conn.cursor(dictionary=True)
    cur.execute('''
        SELECT r.recording_id, r.filename, r.location, r.lead_id, r.user,
               r.length_in_sec, r.start_time, r.end_time, r.vicidial_id,
               v.phone_number, v.campaign_id, v.status AS call_status, v.comments
        FROM recording_log r
        LEFT JOIN vicidial_log v ON r.vicidial_id = v.uniqueid
        WHERE r.end_time IS NOT NULL AND r.length_in_sec >= %s
        ORDER BY r.start_time DESC LIMIT 50
    ''', (MIN_CALL_LENGTH,))
    rows = cur.fetchall()
    cur.close(); conn.close()
    return rows

# ─── Audio pipeline ───────────────────────────────────────────────────────────
def download_recording(url, dest):
    try:
        urllib.request.urlretrieve(url, dest); return True
    except Exception as e:
        log.error("Download failed %s: %s", url, e); return False

def convert_to_wav(mp3, wav):
    r = subprocess.run(['ffmpeg', '-y', '-i', mp3, '-ar', '16000', '-ac', '1', '-c:a', 'pcm_s16le', wav],
        capture_output=True, text=True)
    if r.returncode != 0:
        log.error("ffmpeg: %s", r.stderr[-300:]); return False
    return True

def transcribe(wav):
    r = subprocess.run([WHISPER_BIN, '-m', WHISPER_MODEL, '-f', wav, '--output-txt', '--no-prints'],
        capture_output=True, text=True, timeout=300)
    txt = wav + '.txt'
    if os.path.exists(txt):
        t = open(txt).read().strip(); os.remove(txt); return t or None
    return r.stdout.strip() or None

# ─── CRM webhook ──────────────────────────────────────────────────────────────
def send_to_crm(cls, meta, transcript):
    phone = meta.get('phone_number', 'unknown') or 'unknown'
    payload = json.dumps({
        'email_id':        'call-{}'.format(meta.get('recording_id', '')),
        'from':            '{}@vicidial.local'.format(phone),
        'from_name':       'Caller ({})'.format(phone),
        'subject':         '[CALL] {} - {} - Agent: {}'.format(
                               cls['category'].upper(),
                               meta.get('campaign_id', ''),
                               meta.get('user', '?')),
        'body':            'CALL TRANSCRIPT:\n\n{}\n\n---\nDuration: {}s | Agent: {} | Disposition: {}'.format(
                               transcript,
                               meta.get('length_in_sec', 0),
                               meta.get('user', ''),
                               meta.get('call_status', '')),
        '_ai_action':        cls['action'],
        '_ai_priority':      cls['priority'],
        '_ai_sentiment':     cls['sentiment'],
        '_ai_category':      cls['category'],
        '_ai_summary':       cls['summary'],
        '_ai_alert_message': cls.get('alert_message') or '',
        'source':            'vicidial',
    }).encode()

    req = urllib.request.Request(CRM_WEBHOOK_URL, data=payload, method='POST', headers={
        'Content-Type':     'application/json',
        'Content-Length':   str(len(payload)),
        'X-Webhook-Secret': CRM_WEBHOOK_SECRET,
    })
    try:
        ctx = ssl.create_default_context()
        with urllib.request.urlopen(req, context=ctx, timeout=15) as resp:
            log.info("CRM: %s %s", resp.status, resp.read(300).decode(errors='replace'))
            return True
    except Exception as e:
        log.error("CRM error: %s", e); return False

# ─── Main ─────────────────────────────────────────────────────────────────────
def main():
    state = _init_state()
    recs = get_new_recordings()
    log.info("Found %d recordings to check", len(recs))

    for rec in recs:
        rid = rec['recording_id']
        if _is_processed(state, rid): continue

        log.info("Processing %s: %s (%ss, disp=%s)",
                 rid, rec['filename'], rec['length_in_sec'], rec.get('call_status'))

        with tempfile.TemporaryDirectory() as tmp:
            mp3 = os.path.join(tmp, 'call.mp3')
            wav = os.path.join(tmp, 'call.wav')

            url = rec.get('location', '')
            if not url:
                _mark_processed(state, rid, 'no_url'); continue
            if not download_recording(url, mp3):
                _mark_processed(state, rid, 'dl_failed'); continue
            if not convert_to_wav(mp3, wav):
                _mark_processed(state, rid, 'conv_failed'); continue

            tx = transcribe(wav)
            if not tx:
                _mark_processed(state, rid, 'no_transcript'); continue

            log.info("Transcript %d chars: %s...", len(tx), tx[:80].replace('\n', ' '))

            cls = classify(tx, rec.get('call_status', ''), rec.get('length_in_sec', 0))
            log.info("action=%s priority=%s sentiment=%s category=%s",
                     cls['action'], cls['priority'], cls['sentiment'], cls['category'])

            ok = send_to_crm(cls, rec, tx)
            _mark_processed(state, rid, 'sent' if ok else 'crm_failed')

    state.close()
    log.info("Done.")

if __name__ == '__main__':
    main()
