import argparse
import os
import re
from datetime import datetime
import requests

def search_cloud_file(source_url, keyword, save_output=False):
    """Fetches a remote text file, searches for a keyword case-insensitively, 
    and auto-saves results using the YYYYMMDDsavedSearch####.txt naming convention."""
    print(f"[*] Fetching source: {source_url}")
    try:
        response = requests.get(source_url)
        response.raise_for_status()
        
        lines = response.text.splitlines()
        print(f"[*] Searching for keyword (case-insensitive): '{keyword}'...\n")
        
        lower_keyword = keyword.lower()
        matches = 0
        output_lines = []
        
        for line_num, line in enumerate(lines, start=1):
            if lower_keyword in line.lower():
                match_str = f"[Line {line_num}] {line}"
                print(match_str)
                output_lines.append(match_str + "\n")
                matches += 1
                
        summary_msg = f"\n[*] Search complete. Found {matches} match(es) for '{keyword}'."
        print(summary_msg)
        
        # Auto-save using naming convention if output flag is enabled
        if save_output:
            target_dir = r"C:\Temp\projectLocalSearch\savedSearches"
            os.makedirs(target_dir, exist_ok=True)
            
            # Extract date from source URL (e.g., 20261020 from .../20261020.txt) or fallback to today
            date_str = datetime.now().strftime('%Y%m%d')
            url_match = re.search(r'(\d{8})\.txt$', source_url)
            if url_match:
                date_str = url_match.group(1)
            
            # Scan directory to find the next sequential 4-digit number (####)
            existing_files = os.listdir(target_dir)
            pattern = re.compile(rf'^{date_str}savedSearch(\d{{4}})\.txt$')
            max_seq = 0
            for f in existing_files:
                m = pattern.match(f)
                if m:
                    seq = int(m.group(1))
                    if seq > max_seq:
                        max_seq = seq
            next_seq = max_seq + 1
            seq_str = f"{next_seq:04d}"
            
            # Construct final filename and path
            output_filename = f"{date_str}savedSearch{seq_str}.txt"
            output_path = os.path.join(target_dir, output_filename)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.writelines(output_lines)
                f.write(summary_msg + "\n")
            print(f"[+] Results successfully exported to: {output_path}")

    except requests.exceptions.RequestException as e:
        print(f"[-] Error fetching or accessing the URL: {e}")
    except IOError as e:
        print(f"[-] Error writing to output file: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Search remote text files case-insensitively with automated YYYYMMDDsavedSearch####.txt export.")
    parser.add_argument("-source", required=True, help="URL of the target text file.")
    parser.add_argument("-keyword", required=True, help="Keyword to search for.")
    parser.add_argument("-output", action="store_true", help="Flag to automatically save results under C:\\Temp\\projectLocalSearch\\savedSearches\\ using the naming convention.")
    
    args = parser.parse_args()
    
    search_cloud_file(args.source, args.keyword, args.output)