

# --- CONFIGURATION ---
INPUT_M3U = "playlist.m3u"
OUTPUT_M3U = "safe_playlist.m3u"

def run_autonomous_sanitizer():
    print("=== J.A.R.V.I.S. LOCAL M3U SANITIZER ===\n")
    
    if not os.path.exists(INPUT_M3U):
        print(f"[!] Error: Cannot locate '{INPUT_M3U}'. Please ensure your file is named exactly this and is in the same folder.")
        return

    # 1. Ingest the raw file
    with open(INPUT_M3U, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    username = None
    password = None
    
    # 2. Hunt for credentials by analyzing URL structures
    for line in lines:
        line = line.strip()
        if line.startswith("http"):
            # Strip the protocol to easily count the path slashes
            body = line.split("://", 1)[-1]
            parts = body.split("/")
            
            # Standard XC format: domain/username/password/channel_id(.ts)
            # Or with /live/: domain/live/username/password/channel_id(.ts)
            if len(parts) >= 4:
                if parts[1] == "live":
                    username = parts[2]
                    password = parts[3]
                else:
                    username = parts[1]
                    password = parts[2]
                
                # Once we secure a valid pairing, stop hunting
                if username and password:
                    break

    if not username or not password:
        print("[!] Alert: Could not autonomously detect standard Xtream Codes credentials.")
        return

    print("1. Target locked. Credentials identified in memory for redaction.")
    
    # 3. Execute surgical redaction on the main file
    print("2. Scrubbing M3U file...")
    safe_lines = []
    
    # We create exact string blocks to ensure we don't accidentally replace 
    # a channel name that happens to match the username.
    target_path = f"/{username}/{password}/"
    safe_path = "/YOUR_USER/YOUR_PASS/"
    
    for line in lines:
        # Standard path replacement
        safe_line = line.replace(target_path, safe_path)
        
        # Fallback for query-based URLs (e.g., ?username=...&password=...)
        safe_line = safe_line.replace(f"username={username}", "username=YOUR_USER")
        safe_line = safe_line.replace(f"password={password}", "password=YOUR_PASS")
        
        safe_lines.append(safe_line)

    # 4. Output the safe file for the user
    with open(OUTPUT_M3U, 'w', encoding='utf-8') as f:
        f.writelines(safe_lines)
        
    print(f"3. SUCCESS: Sanitized playlist saved as '{OUTPUT_M3U}'.")
    print("   You may now safely send this file for EPG synchronization. Your login details were not saved.")

if __name__ == "__main__":
    run_autonomous_sanitizer()