#!/usr/bin/env python3
"""
One-shot script: analyze a specific transcribed call and print full results.
Usage: python3 run_single_analysis.py [callid]
"""
import sys
import os
import json
import logging
from dotenv import load_dotenv

load_dotenv()

# Suppress verbose loggers
logging.basicConfig(level=logging.WARNING, format='%(asctime)s [%(levelname)s] %(name)s: %(message)s')
logging.getLogger('analyze_calls_with_parameters').setLevel(logging.INFO)

BID = '6004'
CALLID = sys.argv[1] if len(sys.argv) > 1 else '97393902541773212620'

from config import Config
from db_handler import DatabaseHandler
from analyze_calls_with_parameters import CallAnalyzer

# Build config dict
cfg = Config()
config_dict = {k: getattr(cfg, k) for k in dir(cfg) if k.isupper()}

db = DatabaseHandler(config_dict)
analyzer = CallAnalyzer(config_dict)

print(f"{'='*70}")
print(f"  QUALITY ANALYSIS — BID {BID} | Call: {CALLID}")
print(f"{'='*70}\n")

# Fetch transcript
call_details = db.get_raw_call_details(BID, CALLID)
if not call_details or not call_details.get('transcripts'):
    print(f"ERROR: No transcript found for {CALLID}. Run transcription first.")
    sys.exit(1)

transcript = call_details['transcripts']
speaker_segments = call_details.get('speaker_segments', [])
if isinstance(speaker_segments, str):
    try:
        speaker_segments = json.loads(speaker_segments)
    except Exception:
        speaker_segments = []

actual_duration = call_details.get('duration')
print(f"  Transcript: {len(transcript)} chars")
print(f"  Segments  : {len(speaker_segments) if speaker_segments else 0}")
print(f"  Duration  : {actual_duration}s\n")
print("  Running AWS Nova analysis...\n")

result = analyzer.analyze_call(BID, CALLID, transcript, speaker_segments, actual_duration)

# Save raw result for inspection
with open(f'/tmp/analysis_{CALLID}.json', 'w') as f:
    json.dump(result.get('raw_response', result), f, indent=2)

print(f"{'='*70}")
print("  ANALYSIS RESULTS")
print(f"{'='*70}\n")

print(f"  OVERALL QUALITY SCORE : {result.get('quality_score', 'N/A')} / {result.get('total_possible_score', 'N/A')}")
print(f"  SENTIMENT             : {result.get('sentiment', 'N/A')}")
print(f"  CALL PURPOSE          : {result.get('call_purpose', 'N/A')}")
print()

print("  SUMMARY")
print("  " + "-"*60)
print(f"  {result.get('summary', 'N/A')}\n")

# Quality parameters
raw = result.get('raw_response') or {}
params = raw.get('parameters', {})
param_scores = {}
if isinstance(result.get('parameter_scores'), str):
    try:
        param_scores = json.loads(result['parameter_scores'])
    except Exception:
        pass
elif isinstance(result.get('parameter_scores'), dict):
    param_scores = result['parameter_scores']

if params or param_scores:
    print("  QUALITY PARAMETERS")
    print("  " + "-"*60)
    data = params if params else param_scores
    total_earned = 0
    total_possible = 0
    for pname, pdata in data.items():
        if isinstance(pdata, dict):
            applicable = pdata.get('applicable', True)
            score = pdata.get('score')
            max_score = pdata.get('max_score', pdata.get('max_score', '?'))
            reasoning = pdata.get('reasoning', pdata.get('reasoning', ''))[:100]
            evidence = pdata.get('detected_in_segment', '')[:80]
            timestamp = pdata.get('timestamp', '')
            max_pts = int(max_score) if str(max_score).isdigit() else 0
            if applicable and score is not None:
                total_earned += score
                total_possible += max_pts
                status = f"{score}/{max_score}"
            elif not applicable:
                total_possible += max_pts
                status = "N/A (0)"
            else:
                status = f"?/{max_score}"
            print(f"  • {pname}")
            print(f"    Score: {status}  |  Timestamp: {timestamp}")
            if evidence:
                print(f"    Evidence: \"{evidence}...\"")
            if reasoning:
                print(f"    Reasoning: {reasoning}")
            print()

# Talk-listen ratio
print("  TALK-LISTEN RATIO")
print("  " + "-"*60)
print(f"  Agent talk time   : {result.get('agent_talk_time', 0):.1f}s ({result.get('agent_speak_percentage', 0):.1f}%)")
print(f"  Customer talk time: {result.get('customer_talk_time', 0):.1f}s ({result.get('customer_speak_percentage', 0):.1f}%)")
print(f"  Talk:Listen ratio : {result.get('talk_listen_ratio', 'N/A')}")
print(f"  Dead air          : {result.get('dead_air_percentage', 0):.1f}%")
print(f"  Assessment        : {result.get('talk_listen_assessment', 'N/A')}")
print()

# BANT
print("  BANT ANALYSIS")
print("  " + "-"*60)
customer_profile = raw.get('customer_profile', {})
if customer_profile:
    for field in ['budget', 'authority', 'need', 'timeline']:
        data = customer_profile.get(field, {})
        value = data.get('value', 'Not mentioned')
        evidence = data.get('evidence', 'N/A')[:100]
        confidence = data.get('confidence', 'N/A')
        reasoning = data.get('reasoning', '')[:100]
        print(f"  {field.upper()}")
        print(f"    Value     : {value}")
        print(f"    Evidence  : {evidence}")
        print(f"    Confidence: {confidence}")
        print(f"    Reasoning : {reasoning}")
        print()
    summary = raw.get('customer_profile_summary', '')
    if summary:
        print(f"  BANT Summary: {summary}\n")
else:
    print("  No BANT data available\n")

# Objections
objections = result.get('objections_concerns', '')
if objections:
    print("  OBJECTIONS / CONCERNS")
    print("  " + "-"*60)
    print(f"  {objections}")
    print(f"  Type: {result.get('objection_type', 'N/A')}\n")

print(f"{'='*70}")
print(f"  Full raw response saved to /tmp/analysis_{CALLID}.json")
print(f"  Results saved to 6004_callanalytics + 6004_bant_analysis")
print(f"{'='*70}")
