#!/usr/bin/env python3
"""
Format action log data for better compatibility with Google Docs.
This script takes tab-separated action log data and formats it
for pasting into Google Docs with proper left alignment.
"""

import sys
import re
from typing import List, Tuple

def clean_text(text: str) -> str:
    """Clean and normalize text."""
    if not text:
        return ""
    # Remove extra whitespace but preserve line breaks
    text = re.sub(r'[ \t]+', ' ', text)  # Multiple spaces/tabs to single space
    text = re.sub(r'\n\s*\n', '\n', text)  # Multiple newlines to single
    return text.strip()

def format_for_google_docs(data_lines: List[str]) -> str:
    """
    Format action log data for Google Docs.
    Returns formatted text that can be pasted into Google Docs.
    """
    formatted_lines = []
    
    for line in data_lines:
        line = line.strip()
        if not line:
            continue
            
        # Split by tab
        parts = line.split('\t')
        
        if len(parts) >= 4:
            # Extract columns
            action_no = clean_text(parts[0])
            who = clean_text(parts[1])
            title = clean_text(parts[2])
            action = clean_text(parts[3])
            
            # Format as a table row (tab-separated for Google Docs)
            # Google Docs will recognize tabs and can convert to table
            formatted_line = f"{action_no}\t{who}\t{title}\t{action}"
            formatted_lines.append(formatted_line)
    
    return '\n'.join(formatted_lines)

def create_table_format(data_lines: List[str]) -> str:
    """
    Create a formatted table that's easier to paste into Google Docs.
    Uses a simple text table format.
    """
    rows = []
    
    # Header row
    header = "Action No\tWho\tAction Short Title\tAction"
    rows.append(header)
    rows.append("-" * 80)  # Separator
    
    for line in data_lines:
        line = line.strip()
        if not line:
            continue
            
        parts = line.split('\t')
        if len(parts) >= 4:
            action_no = clean_text(parts[0])
            who = clean_text(parts[1])
            title = clean_text(parts[2])
            action = clean_text(parts[3])
            
            # Replace newlines in action with spaces for table format
            action_single_line = action.replace('\n', ' ').replace('\r', ' ')
            
            row = f"{action_no}\t{who}\t{title}\t{action_single_line}"
            rows.append(row)
    
    return '\n'.join(rows)

def main():
    """Main function to process action log data."""
    
    # Read from stdin or file
    if len(sys.argv) > 1:
        input_file = sys.argv[1]
        try:
            with open(input_file, 'r', encoding='utf-8') as f:
                data_lines = f.readlines()
        except FileNotFoundError:
            print(f"Error: File '{input_file}' not found.", file=sys.stderr)
            sys.exit(1)
    else:
        # Read from stdin
        print("Paste your action log data (tab-separated). Press Ctrl+D (Linux/Mac) or Ctrl+Z (Windows) when done:")
        data_lines = sys.stdin.readlines()
    
    if not data_lines:
        print("No data provided.", file=sys.stderr)
        sys.exit(1)
    
    # Format the data
    formatted_output = format_for_google_docs(data_lines)
    
    # Output to file or stdout
    if len(sys.argv) > 2:
        output_file = sys.argv[2]
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(formatted_output)
        print(f"Formatted data written to: {output_file}")
        print("\nInstructions:")
        print("1. Open the output file")
        print("2. Copy all content (Ctrl+A, Ctrl+C)")
        print("3. Paste into Google Docs (Ctrl+V)")
        print("4. Select all pasted text")
        print("5. Go to Format → Table → Convert text to table")
        print("6. Choose 'Tab' as separator")
        print("7. Right-click table → Table properties → Set cell alignment to Left")
    else:
        print("\n" + "="*80)
        print("FORMATTED DATA (Copy this and paste into Google Docs):")
        print("="*80 + "\n")
        print(formatted_output)
        print("\n" + "="*80)
        print("\nInstructions:")
        print("1. Copy the formatted data above")
        print("2. Paste into Google Docs")
        print("3. Select all pasted text")
        print("4. Go to Format → Table → Convert text to table")
        print("5. Choose 'Tab' as separator")
        print("6. Right-click table → Table properties → Set cell alignment to Left")

if __name__ == "__main__":
    main()


