#!/usr/bin/env python3
"""
Website Change Monitor with Telegram Notifications
Monitors https://tickets.cafonline.com/ for changes and sends notifications via Telegram
"""

import requests
import hashlib
import time
import json
import os
import logging
from datetime import datetime
import argparse
import sys

class WebsiteMonitor:
    def __init__(self, config_file='config.json'):
        self.config_file = config_file
        self.config = self.load_config()
        self.last_hash = None
        self.setup_logging()
        
    def load_config(self):
        """Load configuration from JSON file"""
        try:
            with open(self.config_file, 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            print(f"Configuration file {self.config_file} not found!")
            print("Please create the configuration file with your Telegram bot details.")
            sys.exit(1)
        except json.JSONDecodeError as e:
            print(f"Error parsing configuration file: {e}")
            sys.exit(1)
    
    def setup_logging(self):
        """Setup logging configuration"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler('website_monitor.log'),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)
    
    def get_website_content(self, url):
        """Fetch website content and return it"""
        try:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            response = requests.get(url, headers=headers, timeout=30)
            response.raise_for_status()
            return response.text
        except requests.RequestException as e:
            self.logger.error(f"Error fetching website content: {e}")
            return None
    
    def calculate_hash(self, content):
        """Calculate MD5 hash of content"""
        return hashlib.md5(content.encode('utf-8')).hexdigest()
    
    def send_telegram_notification(self, message):
        """Send notification to Telegram channel/group using direct API calls"""
        try:
            bot_token = self.config['telegram']['bot_token']
            chat_id = self.config['telegram']['chat_id']
            
            url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
            
            payload = {
                'chat_id': chat_id,
                'text': message,
                'parse_mode': 'HTML'
            }
            
            response = requests.post(url, json=payload, timeout=30)
            response.raise_for_status()
            
            self.logger.info("Telegram notification sent successfully")
            return True
        except requests.RequestException as e:
            self.logger.error(f"Error sending Telegram notification: {e}")
            return False
        except Exception as e:
            self.logger.error(f"Unexpected error sending notification: {e}")
            return False
    
    def check_website_changes(self):
        """Check if website content has changed"""
        url = self.config['website']['url']
        self.logger.info(f"Checking website: {url}")
        
        content = self.get_website_content(url)
        if content is None:
            return False
        
        current_hash = self.calculate_hash(content)
        
        if self.last_hash is None:
            self.last_hash = current_hash
            self.logger.info("First run - storing initial hash")
            return False
        
        if current_hash != self.last_hash:
            self.logger.info("Website content has changed!")
            self.last_hash = current_hash
            return True
        
        self.logger.info("No changes detected")
        return False
    
    def format_notification_message(self, url):
        """Format the notification message"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        message = f"""
🚨 <b>Website Change Detected!</b>

🌐 <b>Website:</b> {url}
⏰ <b>Time:</b> {timestamp}

The website content has changed. Check it out!
        """.strip()
        return message
    
    def run_monitor(self):
        """Main monitoring loop"""
        url = self.config['website']['url']
        interval = self.config['monitoring']['check_interval_seconds']
        
        self.logger.info(f"Starting website monitor for {url}")
        self.logger.info(f"Check interval: {interval} seconds")
        
        # Send startup notification
        startup_message = f"""
🤖 <b>Website Monitor Started</b>

🌐 <b>Monitoring:</b> {url}
⏱️ <b>Check Interval:</b> {interval} seconds
⏰ <b>Started at:</b> {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        """.strip()
        
        self.send_telegram_notification(startup_message)
        
        try:
            while True:
                if self.check_website_changes():
                    message = self.format_notification_message(url)
                    self.send_telegram_notification(message)
                
                time.sleep(interval)
                
        except KeyboardInterrupt:
            self.logger.info("Monitor stopped by user")
            shutdown_message = f"""
🛑 <b>Website Monitor Stopped</b>

⏰ <b>Stopped at:</b> {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
            """.strip()
            self.send_telegram_notification(shutdown_message)
        except Exception as e:
            self.logger.error(f"Unexpected error: {e}")
            error_message = f"""
❌ <b>Website Monitor Error</b>

🚨 <b>Error:</b> {str(e)}
⏰ <b>Time:</b> {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
            """.strip()
            self.send_telegram_notification(error_message)

def main():
    parser = argparse.ArgumentParser(description='Website Change Monitor with Telegram Notifications')
    parser.add_argument('--config', default='config.json', help='Configuration file path')
    parser.add_argument('--test', action='store_true', help='Test Telegram notification and exit')
    
    args = parser.parse_args()
    
    monitor = WebsiteMonitor(args.config)
    
    if args.test:
        print("Testing Telegram notification...")
        test_message = f"""
🧪 <b>Test Notification</b>

✅ Telegram bot is working correctly!
⏰ <b>Time:</b> {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
        """.strip()
        
        if monitor.send_telegram_notification(test_message):
            print("✅ Test notification sent successfully!")
        else:
            print("❌ Failed to send test notification")
        return
    
    monitor.run_monitor()

if __name__ == "__main__":
    main()
