import json
from pathlib import Path
from datetime import datetime, time

def cleanup_recent_tracking(tracking_path="data/songlist_tracking.json", cutoff_time_str="11:00"):
    """Remove entries from songlist_tracking.json that were added after the specified time today."""
    tracking_file = Path(tracking_path)
    if not tracking_file.exists():
        print(f"File not found: {tracking_path}")
        return
    
    # Parse cutoff time
    try:
        cutoff_hour, cutoff_minute = map(int, cutoff_time_str.split(":"))
        cutoff_time = time(cutoff_hour, cutoff_minute)
    except ValueError:
        print(f"Invalid time format: {cutoff_time_str}. Use HH:MM format.")
        return
    
    # Load current tracking data
    with open(tracking_file, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    print(f"📋 Loaded {len(data)} entries from songlist_tracking.json")
    print(f"⏰ Removing entries newer than {cutoff_time_str} today...")
    
    # Find entries to remove
    entries_to_remove = []
    for key, entry in data.items():
        downloaded_at = entry.get('downloaded_at')
        if downloaded_at:
            try:
                # Parse the ISO timestamp
                dt = datetime.fromisoformat(downloaded_at.replace('Z', '+00:00'))
                entry_time = dt.time()
                
                # Check if entry is newer than cutoff time
                if entry_time > cutoff_time:
                    entries_to_remove.append(key)
                    print(f"🗑️ Will remove: {entry['artist']} - {entry['title']} (downloaded at {entry_time})")
            except Exception as e:
                print(f"⚠️ Could not parse timestamp for {key}: {e}")
    
    # Remove the entries
    for key in entries_to_remove:
        del data[key]
    
    # Save the cleaned data
    with open(tracking_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    
    print(f"✅ Removed {len(entries_to_remove)} entries")
    print(f"📋 {len(data)} entries remaining in songlist_tracking.json")

if __name__ == "__main__":
    cleanup_recent_tracking() 