# import mysql.connector
# import requests
# from datetime import datetime

# # Telegram credentials
# TELEGRAM_BOT_TOKEN = "1407277292:AAEBSlqqJbMFjxfMjfclsrDMcTTlnM6wu3s"
# TELEGRAM_CHAT_ID = "1100806745"

# # MySQL DB config
# DB_CONFIG = {
#     "host": "dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com",
#     "port": 25060,
#     "user": "kirupa",
#     "password": "revathyks@1982",
#     "database": "skyline_track"
# }

# # Screenshot base URL
# SCREENSHOT_BASE_URL = "https://location.skylinkonline.net/akash/screenshots/"  # <- change this to your actual screenshot URL folder

# def get_screenshot_data():
#     conn = mysql.connector.connect(**DB_CONFIG)
#     cursor = conn.cursor(dictionary=True)

#     today = datetime.now().strftime("%Y-%m-%d")

#     query = """
#         SELECT 
#             e.emp_id, 
#             e.name, 
#             COUNT(s.id) AS screenshot_count,
#             MAX(s.filename) AS sample_file
#         FROM 
#             employee_screenshot s
#         JOIN 
#             employee e ON s.emp_id = e.emp_id
#         WHERE 
#             DATE(s.timestamp) = %s
#         GROUP BY 
#             e.emp_id, e.name
#     """
#     cursor.execute(query, (today,))
#     results = cursor.fetchall()

#     cursor.close()
#     conn.close()
#     return results

# def send_telegram_message(message):
#     url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
#     payload = {
#         "chat_id": TELEGRAM_CHAT_ID,
#         "text": message,
#         "parse_mode": "Markdown",
#         "disable_web_page_preview": True
#     }
#     response = requests.post(url, data=payload)
#     print("Telegram response:", response.text)

# def build_summary():
#     data = get_screenshot_data()
#     if not data:
#         return "No screenshots found for today."

#     today_str = datetime.now().strftime('%Y-%m-%d')
#     summary = f"📊 *Daily Work Screenshot Summary* ({today_str})\n\n"

#     for row in data:
#         name = row["name"]
#         count = row["screenshot_count"] or 0
#         sample_file = row["sample_file"]

#         # Status Indicator
#         if count >= 400:
#             status = "🟢 Excellent"
#         elif count >= 300:
#             status = "🟡 Moderate"
#         else:
#             status = "🔴 Low"

#         # Screenshot link
#         if sample_file:
#             screenshot_url = f"{SCREENSHOT_BASE_URL}{sample_file}"
#             summary += f"👤 *{name}*\n"
#             summary += f"🖼️ Screenshots: [{count}]({screenshot_url})\n"
#         else:
#             summary += f"👤 *{name}*\n"
#             summary += f"🖼️ Screenshots: `{count}`\n"

#         summary += f"{status}\n\n"

#     return summary

# # Run the script
# if __name__ == "__main__":
#     try:
#         report = build_summary()
#         send_telegram_message(report)
#     except Exception as e:
#         print("Error:", e)







# import mysql.connector
# import requests
# from datetime import datetime

# # Telegram credentials
# TELEGRAM_BOT_TOKEN = "1407277292:AAEBSlqqJbMFjxfMjfclsrDMcTTlnM6wu3s"
# TELEGRAM_CHAT_ID = "1100806745"

# # MySQL DB config
# DB_CONFIG = {
#     "host": "dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com",
#     "port": 25060,
#     "user": "kirupa",
#     "password": "revathyks@1982",
#     "database": "skyline_track"
# }

# # Screenshot view base URL (gallery page)
# SCREENSHOT_VIEW_URL = "https://location.skylinkonline.net/akash/screenshots/view.php"  # update with your actual path

# def get_screenshot_data():
#     conn = mysql.connector.connect(**DB_CONFIG)
#     cursor = conn.cursor(dictionary=True)

#     today = datetime.now().strftime("%Y-%m-%d")

#     query = """
#         SELECT 
#             e.emp_id, 
#             e.name, 
#             COUNT(s.id) AS screenshot_count
#         FROM 
#             employee_screenshot s
#         JOIN 
#             employee e ON s.emp_id = e.emp_id
#         WHERE 
#             DATE(s.timestamp) = %s
#         GROUP BY 
#             e.emp_id, e.name
#     """
#     cursor.execute(query, (today,))
#     results = cursor.fetchall()

#     cursor.close()
#     conn.close()
#     return results

# def send_telegram_message(message):
#     url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
#     payload = {
#         "chat_id": TELEGRAM_CHAT_ID,
#         "text": message,
#         "parse_mode": "Markdown",
#         "disable_web_page_preview": False
#     }
#     response = requests.post(url, data=payload)
#     print("Telegram response:", response.text)

# def build_summary():
#     data = get_screenshot_data()
#     if not data:
#         return "No screenshots found for today."

#     today_str = datetime.now().strftime('%Y-%m-%d')
#     summary = f"📊 *Daily Work Screenshot Summary* ({today_str})\n\n"

#     for row in data:
#         emp_id = row["emp_id"]
#         name = row["name"]
#         count = row["screenshot_count"] or 0

#         # Status Indicator
#         if count >= 400:
#             status = "🟢 Excellent"
#         elif count >= 300:
#             status = "🟡 Moderate"
#         else:
#             status = "🔴 Low"

#         # Gallery Link
#         gallery_url = f"{SCREENSHOT_VIEW_URL}?emp_id={emp_id}&date={today_str}"

#         summary += f"👤 *{name}*\n"
#         summary += f"🖼️ Screenshots: [{count}]({gallery_url})\n"
#         summary += f"{status}\n\n"

#     return summary

# # Main
# if __name__ == "__main__":
#     try:
#         report = build_summary()
#         send_telegram_message(report)
#     except Exception as e:
#         print("Error:", e)




# import mysql.connector
# import requests
# import tempfile
# from PIL import Image
# import pytesseract
# from datetime import datetime
# import os
# import re

# # Set path to your Tesseract OCR executable
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# # Telegram credentials
# TELEGRAM_BOT_TOKEN = "1407277292:AAEBSlqqJbMFjxfMjfclsrDMcTTlnM6wu3s"
# TELEGRAM_CHAT_ID = "1100806745"

# # MySQL DB config
# DB_CONFIG = {
#     "host": "dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com",
#     "port": 25060,
#     "user": "kirupa",
#     "password": "revathyks@1982",
#     "database": "skyline_track"
# }

# # Keywords
# PRODUCTIVE_KEYWORDS = [
#     "Excel", "PowerPoint", "Word", "Code", "JIRA", "Outlook", "Project", "ERP", "Documentation",
#     "Meeting", "Zoom", "Teams", "Slack", "Google Docs", "Google Sheets", "Google Slides", "Telegram"
# ]
# DISTRACTING_KEYWORDS = ["YouTube", "Facebook", "Netflix", "Hotstar", "WhatsApp", "Spotify"]

# def classify_text(text):
#     text_lower = text.lower()

#     # Match whole words using regex to reduce false positives
#     if any(re.search(r'\b' + re.escape(word.lower()) + r'\b', text_lower) for word in PRODUCTIVE_KEYWORDS):
#         return "productive"
#     elif any(re.search(r'\b' + re.escape(word.lower()) + r'\b', text_lower) for word in DISTRACTING_KEYWORDS):
#         return "distracting"
#     else:
#         return "idle"

# def get_screenshots_by_emp():
#     conn = mysql.connector.connect(**DB_CONFIG)
#     cursor = conn.cursor(dictionary=True)

#     today = datetime.now().strftime('%Y-%m-%d')
#     query = """
#         SELECT es.emp_id, e.name AS emp_name, es.filename 
#         FROM employee_screenshot es
#         JOIN employee e ON es.emp_id = e.emp_id
#         WHERE DATE(es.timestamp) = %s
#     """
#     cursor.execute(query, (today,))
#     rows = cursor.fetchall()

#     cursor.close()
#     conn.close()

#     emp_files = {}
#     emp_names = {}
#     for row in rows:
#         emp_id = row['emp_id']
#         emp_name = row['emp_name']
#         filename = row['filename']
#         emp_files.setdefault(emp_id, []).append(filename)
#         emp_names[emp_id] = emp_name
#     return emp_files, emp_names

# def analyze_employee(emp_id, files):
#     productive = distracting = idle = 0

#     for filename in files:
#         image_url = f"https://location.skylinkonline.net/akash/screenshots/{filename}"

#         try:
#             print(f"🔗 Trying URL: {image_url}")
#             response = requests.get(image_url, stream=True, timeout=10)
#             if response.status_code != 200:
#                 print(f"⚠️ Cannot download {image_url}")
#                 continue

#             with tempfile.NamedTemporaryFile(mode='wb+', suffix=".png", delete=False) as tmp_file:
#                 tmp_file.write(response.content)
#                 tmp_file.flush()
#                 tmp_path = tmp_file.name

#             try:
#                 image = Image.open(tmp_path)
#                 text = pytesseract.image_to_string(image)
#                 category = classify_text(text)

#                 if category == "productive":
#                     productive += 1
#                 elif category == "distracting":
#                     distracting += 1
#                 else:
#                     idle += 1

#             except Exception as e:
#                 print(f"❌ OCR failed for {image_url}: {e}")

#             finally:
#                 os.remove(tmp_path)

#         except Exception as e:
#             print(f"❌ Error downloading {image_url}: {e}")

#     total = productive + distracting + idle
#     if total == 0:
#         return None

#     ratio = productive / total
#     if ratio >= 0.8:
#         status = "🟢 Excellent"
#         reason = "Most screenshots show productive work apps like Excel, Code, or Meetings."
#     elif ratio >= 0.6:
#         status = "🟡 Moderate"
#         reason = "Mixed productive and distracting activity. Some room for improvement."
#     else:
#         status = "🔴 Low"
#         reason = "High distracting or idle activity like YouTube or empty screens."

#     return productive, distracting, idle, total, status, reason

# def build_summary():
#     emp_files, emp_names = get_screenshots_by_emp()
#     if not emp_files:
#         return "❌ No screenshots found for today."

#     today_str = datetime.now().strftime('%Y-%m-%d')
#     summary = f"📊 *Daily Work Screenshot Summary* ({today_str})\n\n"

#     for emp_id, files in emp_files.items():
#         analysis = analyze_employee(emp_id, files)
#         if not analysis:
#             continue

#         productive, distracting, idle, total, status, reason = analysis
#         emp_name = emp_names.get(emp_id, f"Employee {emp_id}")

#         summary += f"👤 *{emp_name}* (ID: `{emp_id}`)\n"
#         summary += f"🖼️ Screenshots: *{total}* ([View Screenshots](https://location.skylinkonline.net/akash/screenshots/view.php?emp_id={emp_id}&date={today_str}))\n"
#         summary += f"{status}\n"
#         summary += f"📝 Reason: {reason}\n\n"

#     return summary

# def send_telegram_message(message):
#     url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
#     payload = {
#         "chat_id": TELEGRAM_CHAT_ID,
#         "text": message,
#         "parse_mode": "Markdown",
#         "disable_web_page_preview": False
#     }
#     response = requests.post(url, data=payload)
#     print("Telegram response:", response.text)

# # Main
# if __name__ == "__main__":
#     try:
#         report = build_summary()
#         send_telegram_message(report)
#     except Exception as e:
#         print("❌ Error:", e)


# import mysql.connector
# import requests
# import tempfile
# from PIL import Image
# import pytesseract
# from datetime import datetime
# import os
# import json

# # DeepSeek API Config
# API_KEY = 'sk-4f243e0de91e476f858e76469027a404'
# API_URL = 'https://api.deepseek.com/v1/chat/completions'

# # Telegram credentials
# TELEGRAM_BOT_TOKEN = "1407277292:AAEBSlqqJbMFjxfMjfclsrDMcTTlnM6wu3s"
# TELEGRAM_CHAT_ID = "1100806745"

# # Tesseract path
# pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# # MySQL DB config
# DB_CONFIG = {
#     "host": "dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com",
#     "port": 25060,
#     "user": "kirupa",
#     "password": "revathyks@1982",
#     "database": "skyline_track"
# }

# PRODUCTIVE_KEYWORDS = ["Excel", "PowerPoint", "Word", "Code", "JIRA", "Outlook", "Project", "ERP", "Documentation", "Meeting", "Zoom", "Teams", "Slack", "Google Docs", "Google Sheets", "Google Slides", "Telegram","Gmail","GitHub", "Trello", "Asana", "Notion", "Confluence", "Visual Studio Code", "Remote Desktop", "Virtual Machine", "Docker", "Kubernetes", "AWS", "Azure", "Google Cloud", "SQL", "Python", "JavaScript", "HTML", "CSS", "React", "Angular", "Node.js", "Googel Earth", "Google Maps", "Google Calendar", "Google Drive", "Google Meet", "Microsoft Teams", "Microsoft OneDrive", "Microsoft SharePoint", "Microsoft Planner", "Microsoft To Do", "Microsoft Power Automate"]
# DISTRACTING_KEYWORDS = ["YouTube", "Facebook", "Netflix", "Hotstar", "WhatsApp", "Spotify"]

# def classify_text(text):
#     text_lower = text.lower()
#     if any(word.lower() in text_lower for word in PRODUCTIVE_KEYWORDS):
#         return "productive"
#     elif any(word.lower() in text_lower for word in DISTRACTING_KEYWORDS):
#         return "distracting"
#     else:
#         return "idle"

# def call_deepseek_analysis(ocr_text):
#     prompt = f"""
# Analyze the following OCR text from a screenshot and respond with:
# 1. Sentiment (positive/neutral/negative)
# 2. Reason why it's classified as productive/distracting/idle
# 3. Suggestions to improve productivity

# OCR Text:
# \"\"\"{ocr_text}\"\"\"
# Return in this format:
# Sentiment: <sentiment>
# Reason: <reason>
# Suggestions: <tips>
# """
#     headers = {
#         "Authorization": f"Bearer {API_KEY}",
#         "Content-Type": "application/json"
#     }

#     body = {
#         "model": "deepseek-chat",
#         "messages": [{"role": "user", "content": prompt}],
#         "temperature": 0.7
#     }

#     try:
#         response = requests.post(API_URL, headers=headers, data=json.dumps(body))
#         data = response.json()
#         message = data['choices'][0]['message']['content']
#         return message.strip()
#     except Exception as e:
#         return f"DeepSeek error: {e}"

# def get_screenshots_by_emp():
#     conn = mysql.connector.connect(**DB_CONFIG)
#     cursor = conn.cursor(dictionary=True)

#     today = datetime.now().strftime('%Y-%m-%d')
#     cursor.execute("""
#         SELECT emp_id, filename 
#         FROM employee_screenshot 
#         WHERE DATE(timestamp) = %s
#     """, (today,))
#     rows = cursor.fetchall()
#     cursor.close()
#     conn.close()

#     emp_files = {}
#     for row in rows:
#         emp_files.setdefault(row['emp_id'], []).append(row['filename'])
#     return emp_files

# def get_employee_name(emp_id):
#     conn = mysql.connector.connect(**DB_CONFIG)
#     cursor = conn.cursor()
#     cursor.execute("SELECT name FROM employee WHERE emp_id = %s", (emp_id,))
#     result = cursor.fetchone()
#     cursor.close()
#     conn.close()
#     return result[0] if result else "Unknown"

# def analyze_employee(emp_id, files):
#     productive = distracting = idle = 0
#     all_text = []

#     for filename in files:
#         image_url = f"https://location.skylinkonline.net/akash/screenshots/{filename}"
#         try:
#             response = requests.get(image_url, stream=True, timeout=10)
#             if response.status_code != 200:
#                 continue

#             with tempfile.NamedTemporaryFile(mode='wb+', suffix=".png", delete=False) as tmp_file:
#                 tmp_file.write(response.content)
#                 tmp_path = tmp_file.name

#             try:
#                 image = Image.open(tmp_path)
#                 text = pytesseract.image_to_string(image)
#                 all_text.append(text.strip())
#                 category = classify_text(text)

#                 if category == "productive":
#                     productive += 1
#                 elif category == "distracting":
#                     distracting += 1
#                 else:
#                     idle += 1
#             finally:
#                 os.remove(tmp_path)
#         except Exception as e:
#             print(f"❌ Error processing {image_url}: {e}")

#     total = productive + distracting + idle
#     if total == 0:
#         return None

#     ratio = productive / total
#     if ratio >= 0.8:
#         status = "🟢 High"
#     elif ratio >= 0.6:
#         status = "🟡 Moderate"
#     else:
#         status = "🔴 Low"

#     # DeepSeek reasoning
#     combined_text = "\n".join(all_text)
#     deepseek_result = call_deepseek_analysis(combined_text)
#     return productive, distracting, idle, total, status, deepseek_result

# def build_summary():
#     emp_files = get_screenshots_by_emp()
#     if not emp_files:
#         return "❌ No screenshots found for today."

#     today_str = datetime.now().strftime('%Y-%m-%d')
#     summary = f"📊 *Daily Work Screenshot Summary* ({today_str})\n\n"

#     for emp_id, files in emp_files.items():
#         result = analyze_employee(emp_id, files)
#         if not result:
#             continue

#         productive, distracting, idle, total, status, deepseek_text = result
#         emp_name = get_employee_name(emp_id)
#         view_link = f"https://location.skylinkonline.net/akash/screenshots/view.php?emp_id={emp_id}&date={today_str}"

#         summary += f"👤 *{emp_name}* (ID: `{emp_id}`)\n"
#         summary += f"🖼️ Screenshots: *{total}* ([View Screenshots]({view_link}))\n"
#         summary += f"{status}\n"
#         summary += f"📝 {deepseek_text}\n\n"

#     return summary

# def send_telegram_message(message):
#     url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
#     payload = {
#         "chat_id": TELEGRAM_CHAT_ID,
#         "text": message,
#         "parse_mode": "Markdown",
#         "disable_web_page_preview": False
#     }
#     response = requests.post(url, data=payload)
#     print("Telegram response:", response.text)

# # Main
# if __name__ == "__main__":
#     try:
#         report = build_summary()
#         MAX_LENGTH = 4000
#         for i in range(0, len(report), MAX_LENGTH):
#             chunk = report[i:i+MAX_LENGTH]
#             send_telegram_message(chunk)
#     except Exception as e:
#         print("❌ Error:", e)

# import os
# import requests
# import mysql.connector
# import pytesseract
# from datetime import datetime
# from PIL import Image
# from urllib.parse import quote
# from deepseek_api import analyze_text  # assuming you have a custom wrapper

# # Set tesseract path for Windows
# pytesseract.pytesseract.tesseract_cmd = r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe"

# # Configs
# TELEGRAM_BOT_TOKEN = '1407277292:AAEBSlqqJbMFjxfMjfclsrDMcTTlnM6wu3s'
# TELEGRAM_CHAT_ID = '1100806745'
# DB_CONFIG = {
#     'host': 'dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com',
#     'user': 'kirupa',
#     'port': 25060,
#     'password': 'revathyks@1982',
#     'database': 'skyline_track'
# }
# SCREENSHOT_DIR = '/var/www/html/akash/screenshots/'
# BASE_URL = 'https://location.skylinkonline.net/akash/screenshots/'

# # Connect to MySQL
# def get_db_connection():
#     return mysql.connector.connect(**DB_CONFIG)

# # Get employee name from ID
# def get_employee_name(emp_id):
#     conn = get_db_connection()
#     cursor = conn.cursor()
#     cursor.execute("SELECT name FROM employee WHERE emp_id = %s", (emp_id,))
#     row = cursor.fetchone()
#     conn.close()
#     return row[0] if row else f"Unknown ({emp_id})"

# # Get screenshot list grouped by employee ID
# def get_screenshots_by_emp():
#     today = datetime.now().strftime('%Y-%m-%d')
#     conn = get_db_connection()
#     cursor = conn.cursor()
#     cursor.execute("SELECT emp_id, filename FROM employee_screenshot WHERE DATE(timestamp) = %s", (today,))
#     rows = cursor.fetchall()
#     conn.close()

#     data = {}
#     for emp_id, file_path in rows:
#         data.setdefault(emp_id, []).append(file_path)
#     return data

# # Analyze a single screenshot

# def extract_text_from_image(path):
#     try:
#         return pytesseract.image_to_string(Image.open(path))
#     except Exception as e:
#         print(f"OCR failed for {path}: {e}")
#         return ""

# # Analyze employee activity
# def analyze_employee(emp_id, files):
#     texts = []
#     for file in files:
#         full_path = os.path.join(SCREENSHOT_DIR, file)
#         if os.path.exists(full_path):
#             texts.append(extract_text_from_image(full_path))

#     full_text = "\n".join(texts).strip()
#     if not full_text:
#         sentiment = "neutral"
#         reason = "The OCR text is completely empty, indicating no content to analyze for sentiment or productivity impact."
#         suggestions = [
#             "Ensure the OCR tool is correctly capturing text from the screenshot.",
#             "Verify if the screenshot contains any visible text or if it’s blank.",
#             "If working on a task, double-check the source material for content to avoid idle time."
#         ]
#     else:
#         sentiment, reason, suggestions = analyze_text(full_text)

#     status_emoji = {
#         'positive': '🟢 High',
#         'neutral': '🟡 Moderate',
#         'negative': '🔴 Low'
#     }

#     return len(files), status_emoji.get(sentiment.lower(), '⚪ Unknown'), sentiment.capitalize(), reason, suggestions

# # Send message to Telegram
# def send_telegram_message(message):
#     url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
#     payload = {
#         "chat_id": TELEGRAM_CHAT_ID,
#         "text": message,
#         "parse_mode": "Markdown",
#         "disable_web_page_preview": False
#     }
#     response = requests.post(url, data=payload)
#     print("Telegram response:", response.text)

# # Build and send summary

# def build_and_send_summary():
#     emp_files = get_screenshots_by_emp()
#     if not emp_files:
#         send_telegram_message("❌ No screenshots found for today.")
#         return

#     today_str = datetime.now().strftime('%Y-%m-%d')

#     for emp_id, files in emp_files.items():
#         total, status, sentiment, reason, suggestions = analyze_employee(emp_id, files)
#         emp_name = get_employee_name(emp_id)

#         message = f"👤 *{emp_name}* (ID: `{emp_id}`)\n"
#         message += f"🖼️ Screenshots: *{total}* ([View Screenshots]({BASE_URL}view.php?emp_id={emp_id}&date={today_str}))\n"
#         message += f"{status}\n"
#         message += f"📝 *Sentiment:* {sentiment}  \n"
#         message += f"*Reason:* {reason}\n\n"

#         if suggestions:
#             message += "*Suggestions:*\n"
#             for idx, s in enumerate(suggestions, start=1):
#                 message += f"{idx}. {s}\n"

#         send_telegram_message(message)

# # Entry point
# if __name__ == '__main__':
#     try:
#         build_and_send_summary()
#     except Exception as e:
#         print(f"❌ Error: {e}")

import os
import pymysql
import requests
import pytesseract
from PIL import Image
from datetime import datetime
from io import BytesIO

# ---------- CONFIGURATION ----------
DB_CONFIG = {
    'host': 'dbaas-db-1602524-do-user-4209794-0.b.db.ondigitalocean.com',
    'user': 'kirupa',
    'port': 25060,
    'password': 'revathyks@1982',
    'database': 'skyline_track'
}

TELEGRAM_BOT_TOKEN = '1407277292:AAEBSlqqJbMFjxfMjfclsrDMcTTlnM6wu3s'
TELEGRAM_CHAT_ID = '-4834670050'
# TELEGRAM_CHAT_ID = '1100806745'

TESSERACT_PATH = r"C:\\Program Files\\Tesseract-OCR\\tesseract.exe"
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH

DEEPSEEK_API_KEY = 'sk-4f243e0de91e476f858e76469027a404'
DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'

SCREENSHOT_URL_BASE = 'https://location.skylinkonline.net/akash/screenshots/'
VIEW_SCREENSHOT_LINK = 'https://location.skylinkonline.net/akash/screenshots/view.php?emp_id={emp_id}&date={date}'

TODAY = datetime.now().strftime('%Y-%m-%d')

# ---------- DEEPSEEK WRAPPER ----------
def analyze_with_deepseek(text, emp_name):
    prompt = f"""
    Employee: {emp_name}
    OCR Text:
    {text}

    Analyze the OCR and summarize the following:
    - Sentiment (1 line)
    - 2-3 Key Reasons for the sentiment
    - 2-3 Suggestions for better productivity

    Respond concisely in bullet points. Avoid long paragraphs.
    """

    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {DEEPSEEK_API_KEY}'
    }
    data = {
        'model': 'deepseek-chat',
        'messages': [
            {'role': 'user', 'content': prompt}
        ],
        'temperature': 0.7
    }
    response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
    result = response.json()
    return result['choices'][0]['message']['content']

# ---------- DB CONNECTION ----------
def get_connection():
    return pymysql.connect(**DB_CONFIG)

# ---------- FORMAT REPORT ----------
def format_employee_report(emp_id, emp_name, screenshot_count, view_link, deepseek_summary):
    return f"""
👤 *{emp_name}* (ID: `{emp_id}`)
🖼️ *Screenshots*: {screenshot_count} ([View Screenshots]({view_link}))

{deepseek_summary.strip()}

🧠 *Takeaway*: Stay focused and structure tasks with tools for better results.
    """.strip()

# ---------- OCR + REPORT PER EMPLOYEE ----------
def generate_daily_report():
    conn = get_connection()
    cursor = conn.cursor(pymysql.cursors.DictCursor)

    cursor.execute("SELECT DISTINCT emp_id FROM employee_screenshot WHERE DATE(timestamp) = %s", (TODAY,))
    employees = cursor.fetchall()

    for emp in employees:
        emp_id = emp['emp_id']

        cursor.execute("SELECT name FROM employee WHERE emp_id = %s", (emp_id,))
        emp_name_result = cursor.fetchone()
        emp_name = emp_name_result['name'] if emp_name_result else f"Employee {emp_id}"

        cursor.execute("SELECT filename FROM employee_screenshot WHERE emp_id = %s AND DATE(timestamp) = %s", (emp_id, TODAY))
        screenshots = cursor.fetchall()

        ocr_text = ""
        for sc in screenshots:
            try:
                url = SCREENSHOT_URL_BASE + sc['filename']
                response = requests.get(url)
                img = Image.open(BytesIO(response.content))
                ocr_text += pytesseract.image_to_string(img)
            except Exception as e:
                print(f"OCR failed for {url}: {e}")

        if not ocr_text.strip():
            ocr_text = "No readable content from OCR."

        deepseek_summary = analyze_with_deepseek(ocr_text, emp_name)

        total_screens = len(screenshots)
        view_link = VIEW_SCREENSHOT_LINK.format(emp_id=emp_id, date=TODAY)

        msg = format_employee_report(emp_id, emp_name, total_screens, view_link, deepseek_summary)
        send_telegram_message(msg)

    cursor.close()
    conn.close()

# ---------- TELEGRAM SEND ----------
def send_telegram_message(message):
    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
    data = {
        'chat_id': TELEGRAM_CHAT_ID,
        'text': message,
        'parse_mode': 'Markdown'
    }
    response = requests.post(url, data=data)
    if response.status_code != 200:
        print("Telegram Error:", response.text)

# ---------- MAIN ----------
if __name__ == '__main__':
    generate_daily_report()






 

