#!/usr/bin/env python3
"""
Audit Watcher: Runs the ELA audit and sends a Telegram message if issues are found.
"""
import os
import subprocess
import sys
import shlex

# Configuration
BASE_DIR = os.path.expanduser('~/Home_School/2nd_Grade/English_Language_Arts')
AUDIT_SCRIPT = os.path.expanduser('~/Home_School/2nd_Grade/English_Language_Arts/../.hermes/skills/education/ela-week-audit/scripts/audit_all_weeks.py')
# Fallback: use the skill's canonical path
if not os.path.exists(AUDIT_SCRIPT):
    AUDIT_SCRIPT = os.path.expanduser('~/.hermes/skills/education/ela-week-audit/scripts/audit_all_weeks.py')
TELEGRAM_TARGET = 'telegram' 

def run_audit():
    print(f"--- Starting ELA Audit: {BASE_DIR} ---")
    try:
        # Run the audit script and capture output
        result = subprocess.run(
            [sys.executable, AUDIT_SCRIPT],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout, 0
    except subprocess.CalledProcessError as e:
        return e.stdout + e.stderr, 1
    except Exception as e:
        return str(e), 1

def main():
    output, return_code = run_audit()
    print(output)

    # Check if there are failures in the output
    # The script prints "FAIL: X" and "Total issues: Y"
    has_failures = "FAIL:" in output or "issues" in output.lower()

    if has_failures or return_code != 0:
        print("⚠️ Issues detected. Sending alert to Telegram...")
        
        # Create a summary for the message
        summary_lines = output.strip().split('\n')[-8:] # Take a slightly larger slice for context
        summary = "\n".join(summary_lines)
        
        # Constructing Markdown for Telegram
        message = f"🚨 *ELA Curriculum Audit Alert*\n\n```\n{summary}\n```\n\nPlease check the audit logs."
        
        # Use the terminal to call the hermes command to send the message
        # We use shell quoting to be safe.
        escaped_msg = shlex.quote(message)
        
        # Using 'hermes send --to <target> <message>'
        # Note: '--to' is the correct flag based on 'hermes send --help'
        cmd = f"hermes send --to {TELEGRAM_TARGET} {escaped_msg}"
        
        try:
            # Run as subprocess. We use shell=True because we are passing a single command string with shell quoting.
            subprocess.run(cmd, shell=True, check=True)
            print("✅ Alert sent successfully.")
        except subprocess.CalledProcessError:
            print("❌ Failed to send Telegram alert. Check hermes CLI configuration.")
            sys.exit(1)
    else:
        print("✅ Audit passed. No issues found.")

if __name__ == "__main__":
    main()