#!/usr/bin/env python3
"""
Push-up Reminder System
Daily tracking and notifications
"""

import sqlite3
from datetime import datetime, timedelta
import os
from dotenv import load_dotenv

load_dotenv()

class PushupTracker:
    """Track daily push-up progress"""

    def __init__(self):
        self.db_conn = self._init_database()
        self.daily_goal = 200

    def _init_database(self):
        """Initialize SQLite database"""
        conn = sqlite3.connect('pushups.db')
        cursor = conn.cursor()

        cursor.execute('''
            CREATE TABLE IF NOT EXISTS pushups (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT UNIQUE,
                count INTEGER DEFAULT 0,
                sets INTEGER DEFAULT 0,
                completed INTEGER DEFAULT 0,
                notes TEXT
            )
        ''')

        cursor.execute('''
            CREATE TABLE IF NOT EXISTS reminders (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp TEXT,
                message TEXT,
                sent INTEGER DEFAULT 0
            )
        ''')

        conn.commit()
        return conn

    def log_set(self, count, notes=''):
        """Log a set of push-ups"""
        today = datetime.now().strftime('%Y-%m-%d')
        cursor = self.db_conn.cursor()

        # Get today's record
        cursor.execute('SELECT count, sets FROM pushups WHERE date = ?', (today,))
        result = cursor.fetchone()

        if result:
            new_count = result[0] + count
            new_sets = result[1] + 1
            completed = 1 if new_count >= self.daily_goal else 0

            cursor.execute('''
                UPDATE pushups
                SET count = ?, sets = ?, completed = ?, notes = ?
                WHERE date = ?
            ''', (new_count, new_sets, completed, notes, today))
        else:
            completed = 1 if count >= self.daily_goal else 0
            cursor.execute('''
                INSERT INTO pushups (date, count, sets, completed, notes)
                VALUES (?, ?, 1, ?, ?)
            ''', (today, count, completed, notes))

        self.db_conn.commit()

        # Get updated stats
        cursor.execute('SELECT count FROM pushups WHERE date = ?', (today,))
        total_today = cursor.fetchone()[0]

        remaining = max(0, self.daily_goal - total_today)

        print(f"✅ Logged {count} push-ups")
        print(f"📊 Today's total: {total_today}/{self.daily_goal}")

        if remaining > 0:
            print(f"💪 {remaining} more to go!")
            self._send_reminder(f"Keep going! {remaining} push-ups remaining today")
        else:
            print(f"🎉 Daily goal completed!")
            self._send_reminder("🎉 Congratulations! Daily goal completed!")

        return total_today

    def get_streak(self):
        """Calculate current streak"""
        cursor = self.db_conn.cursor()
        cursor.execute('''
            SELECT date, completed
            FROM pushups
            WHERE completed = 1
            ORDER BY date DESC
        ''')

        results = cursor.fetchall()

        if not results:
            return 0

        streak = 0
        current_date = datetime.now().date()

        for date_str, completed in results:
            date = datetime.strptime(date_str, '%Y-%m-%d').date()

            if date == current_date or (current_date - date).days == 1:
                streak += 1
                current_date = date - timedelta(days=1)
            else:
                break

        return streak

    def get_statistics(self):
        """Get overall statistics"""
        cursor = self.db_conn.cursor()

        # Total push-ups
        cursor.execute('SELECT SUM(count) FROM pushups')
        total = cursor.fetchone()[0] or 0

        # Days completed
        cursor.execute('SELECT COUNT(*) FROM pushups WHERE completed = 1')
        days_completed = cursor.fetchone()[0]

        # Current streak
        streak = self.get_streak()

        # Today's progress
        today = datetime.now().strftime('%Y-%m-%d')
        cursor.execute('SELECT count, completed FROM pushups WHERE date = ?', (today,))
        today_result = cursor.fetchone()
        today_count = today_result[0] if today_result else 0
        today_completed = today_result[1] if today_result else 0

        return {
            'total_pushups': total,
            'days_completed': days_completed,
            'current_streak': streak,
            'today_count': today_count,
            'today_completed': bool(today_completed),
            'today_remaining': max(0, self.daily_goal - today_count)
        }

    def print_statistics(self):
        """Print formatted statistics"""
        stats = self.get_statistics()

        print("\n" + "="*50)
        print("💪 PUSH-UP TRACKER STATISTICS")
        print("="*50)
        print(f"Total Push-ups: {stats['total_pushups']}")
        print(f"Days Completed: {stats['days_completed']}")
        print(f"Current Streak: {stats['current_streak']} days 🔥")
        print(f"\nToday's Progress: {stats['today_count']}/{self.daily_goal}")

        if stats['today_completed']:
            print("Status: ✅ COMPLETED")
        else:
            print(f"Status: ⏳ IN PROGRESS ({stats['today_remaining']} remaining)")

        print("="*50 + "\n")

    def _send_reminder(self, message):
        """Send reminder notification"""
        timestamp = datetime.now().isoformat()

        # Log reminder
        cursor = self.db_conn.cursor()
        cursor.execute('''
            INSERT INTO reminders (timestamp, message, sent)
            VALUES (?, ?, 0)
        ''', (timestamp, message))
        self.db_conn.commit()

        # Try to send via Telegram
        try:
            import requests

            bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
            chat_id = os.getenv('TELEGRAM_CHAT_ID')

            if bot_token and chat_id:
                url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
                payload = {
                    'chat_id': chat_id,
                    'text': f"💪 {message}",
                    'parse_mode': 'HTML'
                }

                response = requests.post(url, json=payload)

                if response.status_code == 200:
                    cursor.execute('''
                        UPDATE reminders
                        SET sent = 1
                        WHERE timestamp = ?
                    ''', (timestamp,))
                    self.db_conn.commit()
                    print("📱 Reminder sent via Telegram")
        except Exception as e:
            print(f"⚠️ Could not send Telegram reminder: {e}")

    def close(self):
        """Close database connection"""
        self.db_conn.close()


def main():
    """Main entry point"""
    import argparse

    parser = argparse.ArgumentParser(description='Push-up Tracker & Reminder')
    parser.add_argument('--log', type=int, metavar='COUNT',
                       help='Log a set of push-ups')
    parser.add_argument('--notes', type=str, default='',
                       help='Add notes to the set')
    parser.add_argument('--stats', action='store_true',
                       help='Show statistics')
    parser.add_argument('--streak', action='store_true',
                       help='Show current streak')

    args = parser.parse_args()

    tracker = PushupTracker()

    try:
        if args.log:
            tracker.log_set(args.log, args.notes)

        if args.streak:
            streak = tracker.get_streak()
            print(f"🔥 Current streak: {streak} days")

        if args.stats or not args.log:
            tracker.print_statistics()
    finally:
        tracker.close()


if __name__ == '__main__':
    main()
