#!/usr/bin/env python3
"""
BetPredictAI - Main Scheduler

Orchestrates all automated tasks:
1. Live score checking (every 5 min during match hours)
2. Prediction generation (every 6 hours)
3. Model retraining (weekly)
4. Data cleanup and maintenance

Uso:
  python3 scheduler.py                    # Run all appropriate tasks
  python3 scheduler.py --verify           # Only run verification
  python3 scheduler.py --predict          # Only generate predictions
  python3 scheduler.py --status           # Show system status
"""

import os
import sys
import json
import subprocess
from datetime import datetime, timedelta
import logging

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[
        logging.FileHandler('/var/www/html/bet.cuttalo.com/logs/scheduler.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, '..', 'data')
LOGS_DIR = os.path.join(BASE_DIR, '..', 'logs')

# Ensure directories exist
os.makedirs(LOGS_DIR, exist_ok=True)

# Schedule configuration
MATCH_HOURS_START = 12  # Matches typically start from 12:00
MATCH_HOURS_END = 23    # Until 23:00
VERIFY_INTERVAL_MINUTES = 5
PREDICT_INTERVAL_HOURS = 6


def get_scheduler_state():
    """Load scheduler state from file"""
    state_path = os.path.join(DATA_DIR, 'scheduler_state.json')
    if os.path.exists(state_path):
        with open(state_path) as f:
            return json.load(f)
    return {
        'last_verify': None,
        'last_predict': None,
        'last_retrain': None,
        'verify_count_today': 0,
        'errors_today': 0
    }


def save_scheduler_state(state):
    """Save scheduler state"""
    state_path = os.path.join(DATA_DIR, 'scheduler_state.json')
    state['updated_at'] = datetime.now().isoformat()
    with open(state_path, 'w') as f:
        json.dump(state, f, indent=2)


def is_match_time():
    """Check if current time is within typical match hours"""
    now = datetime.now()
    hour = now.hour
    weekday = now.weekday()  # 0=Monday, 6=Sunday

    # Weekend has more matches throughout the day
    if weekday >= 5:  # Saturday or Sunday
        return 11 <= hour <= 23

    # Weekday matches are typically evening
    return 17 <= hour <= 23


def should_run_verification(state):
    """Check if we should run live score verification"""
    last_verify = state.get('last_verify')

    if not last_verify:
        return True

    try:
        last_dt = datetime.fromisoformat(last_verify)
        elapsed = (datetime.now() - last_dt).total_seconds() / 60

        # During match hours: every 5 minutes
        if is_match_time():
            return elapsed >= VERIFY_INTERVAL_MINUTES

        # Outside match hours: every 30 minutes
        return elapsed >= 30

    except Exception:
        return True


def should_run_predictions(state):
    """Check if we should generate new predictions"""
    last_predict = state.get('last_predict')

    if not last_predict:
        return True

    try:
        last_dt = datetime.fromisoformat(last_predict)
        elapsed = (datetime.now() - last_dt).total_seconds() / 3600

        return elapsed >= PREDICT_INTERVAL_HOURS

    except Exception:
        return True


def run_live_verification():
    """Run live score checker"""
    logger.info("Running live score verification...")

    try:
        result = subprocess.run(
            ['python3', 'live_score_checker.py'],
            cwd=BASE_DIR,
            capture_output=True,
            text=True,
            timeout=300
        )

        if result.returncode == 0:
            logger.info("Verification completed successfully")
            return True
        else:
            logger.error(f"Verification failed: {result.stderr}")
            return False

    except subprocess.TimeoutExpired:
        logger.error("Verification timed out")
        return False
    except Exception as e:
        logger.error(f"Verification error: {e}")
        return False


def run_prediction_generator():
    """Run fixture collector to generate new predictions"""
    logger.info("Running prediction generator...")

    try:
        result = subprocess.run(
            ['python3', 'fixture_collector.py'],
            cwd=BASE_DIR,
            capture_output=True,
            text=True,
            timeout=600
        )

        if result.returncode == 0:
            logger.info("Predictions generated successfully")
            return True
        else:
            logger.error(f"Prediction generation failed: {result.stderr}")
            return False

    except subprocess.TimeoutExpired:
        logger.error("Prediction generation timed out")
        return False
    except Exception as e:
        logger.error(f"Prediction error: {e}")
        return False


def show_status():
    """Display system status"""
    state = get_scheduler_state()
    verification = load_verification_stats()

    print("\n" + "=" * 60)
    print("BetPredictAI System Status")
    print("=" * 60)

    print(f"\nCurrent Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"Match Hours Active: {'Yes' if is_match_time() else 'No'}")

    print("\nLast Operations:")
    print(f"  Last Verification: {state.get('last_verify', 'Never')}")
    print(f"  Last Predictions:  {state.get('last_predict', 'Never')}")
    print(f"  Last Retrain:      {state.get('last_retrain', 'Never')}")

    print(f"\nVerifications Today: {state.get('verify_count_today', 0)}")
    print(f"Errors Today:        {state.get('errors_today', 0)}")

    if verification:
        print("\nVerification Stats:")
        print(f"  Total Matches:  {verification.get('total', 0)}")
        print(f"  Correct:        {verification.get('correct', 0)}")
        print(f"  Accuracy:       {verification.get('accuracy', 0)}%")

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


def load_verification_stats():
    """Load verification statistics"""
    path = os.path.join(DATA_DIR, 'verification_results.json')
    if os.path.exists(path):
        with open(path) as f:
            data = json.load(f)
            return data.get('summary', {})
    return {}


def main():
    """Main scheduler entry point"""
    args = sys.argv[1:]

    # Handle specific commands
    if '--status' in args:
        show_status()
        return

    if '--verify' in args:
        run_live_verification()
        return

    if '--predict' in args:
        run_prediction_generator()
        return

    # Regular scheduled run
    logger.info("=" * 60)
    logger.info("BetPredictAI Scheduler")
    logger.info(f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    logger.info(f"Match Hours: {'Active' if is_match_time() else 'Inactive'}")
    logger.info("=" * 60)

    state = get_scheduler_state()

    # Reset daily counters
    today = datetime.now().strftime('%Y-%m-%d')
    if state.get('last_date') != today:
        state['verify_count_today'] = 0
        state['errors_today'] = 0
        state['last_date'] = today

    # Run verification if needed
    if should_run_verification(state):
        success = run_live_verification()
        state['last_verify'] = datetime.now().isoformat()
        state['verify_count_today'] = state.get('verify_count_today', 0) + 1
        if not success:
            state['errors_today'] = state.get('errors_today', 0) + 1

    # Run predictions if needed
    if should_run_predictions(state):
        success = run_prediction_generator()
        state['last_predict'] = datetime.now().isoformat()
        if not success:
            state['errors_today'] = state.get('errors_today', 0) + 1

    # Save state
    save_scheduler_state(state)

    logger.info("Scheduler run completed")


if __name__ == '__main__':
    main()
