#!/usr/bin/env python3
"""
MTG Rules Update Check Script

This script checks for updates to the MTG rules repository and applies them
if available. It's designed to be run weekly via cron or manually.

Usage:
    python update_check.py [--check] [--apply] [--scan] [--weekly]
"""

import sys
import os
import json
import logging
from datetime import datetime
from pathlib import Path

# Add parent directory to path for importing mtg_rules_engine
sys.path.insert(0, str(Path(__file__).parent.parent))

from mtg_rules_engine.updater import RulesUpdater

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('/home/user/wall-o/mtg_rules_engine/updater.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


def check_for_updates(updater: RulesUpdater) -> dict:
    """Check for updates and return results."""
    logger.info("Checking for rules updates...")
    
    updates = updater.check_for_updates()
    
    if updates['has_updates']:
        logger.info(f"Updates available! Current: {updates['current_version']}, Latest: {updates['latest_version']}")
    else:
        logger.info(f"No updates available. Current version: {updates['current_version']}")
    
    return updates


def apply_updates(updater: RulesUpdater) -> bool:
    """Apply updates if available."""
    logger.info("Applying rules updates...")
    
    try:
        updater.apply_updates()
        logger.info("Updates applied successfully")
        return True
    except Exception as e:
        logger.error(f"Failed to apply updates: {e}")
        return False


def scan_rules(updater: RulesUpdater) -> dict:
    """Scan and validate the rules repository."""
    logger.info("Scanning rules repository...")
    
    result = updater.scan_rules()
    
    if result['status'] == 'success':
        logger.info(f"Rules scan successful: {result['rules_count']} rules found")
    else:
        logger.error(f"Rules scan failed: {result['message']}")
        if result['errors']:
            logger.error(f"Errors: {result['errors']}")
    
    return result


def run_weekly_check():
    """Run the weekly update check."""
    logger.info("Running weekly update check...")
    
    updater = RulesUpdater()
    
    # Check for updates
    updates = check_for_updates(updater)
    
    if updates['has_updates']:
        # Apply updates
        success = apply_updates(updater)
        
        if success:
            logger.info("Weekly update check completed successfully")
        else:
            logger.error("Weekly update check failed")
            sys.exit(1)
    else:
        logger.info("No updates needed")
    
    # Scan rules to ensure they're valid
    scan_result = scan_rules(updater)
    
    if scan_result['status'] != 'success':
        logger.error("Rules validation failed after update")
        sys.exit(1)


def main():
    """Main entry point."""
    import argparse
    
    parser = argparse.ArgumentParser(description="MTG Rules Update Check")
    parser.add_argument('--check', action='store_true', help='Check for updates only')
    parser.add_argument('--apply', action='store_true', help='Apply updates')
    parser.add_argument('--scan', action='store_true', help='Scan rules only')
    parser.add_argument('--weekly', action='store_true', help='Run weekly check')
    parser.add_argument('--initialize', action='store_true', help='Initialize the updater')
    
    args = parser.parse_args()
    
    updater = RulesUpdater()
    
    if args.initialize:
        logger.info("Initializing rules updater...")
        try:
            updater.initialize()
            logger.info("Initialization complete")
        except Exception as e:
            logger.error(f"Initialization failed: {e}")
            sys.exit(1)
    
    elif args.check:
        updates = check_for_updates(updater)
        print(json.dumps(updates, indent=2))
    
    elif args.apply:
        success = apply_updates(updater)
        if not success:
            sys.exit(1)
    
    elif args.scan:
        result = scan_rules(updater)
        print(json.dumps(result, indent=2))
    
    elif args.weekly:
        run_weekly_check()
    
    else:
        # Default: run weekly check
        run_weekly_check()


if __name__ == "__main__":
    main()
