import os
import win32com.client
import json

def escape_js_string(s):
    if not s:
        return ""
    return json.dumps(s)[1:-1] # Use json.dumps to handle escaping, then strip quotes

def extract_comments_to_js(doc_paths):
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = False
    
    # Constants
    wdVerticalPositionRelativeToPage = 6
    wdHorizontalPositionRelativeToPage = 5
    
    try:
        for doc_path in doc_paths:
            if not os.path.exists(doc_path):
                print(f"File not found: {doc_path}")
                continue
                
            abs_path = os.path.abspath(doc_path)
            js_path = os.path.splitext(abs_path)[0] + "_comments.js"
            
            print(f"Processing: {os.path.basename(doc_path)}")
            
            try:
                doc = word.Documents.Open(abs_path)
                
                js_content = ["/* Run this script in Bluebeam Revu (Ctrl+J) */", "console.println('Starting import...');"]
                
                comment_count = doc.Comments.Count
                print(f"  Found {comment_count} comments.")
                
                if comment_count == 0:
                    doc.Close(SaveChanges=False)
                    continue

                for i in range(1, comment_count + 1):
                    comment = doc.Comments(i)
                    rng = comment.Scope
                    
                    # Get Page Number (1-based)
                    page_num = rng.Information(3) # wdActiveEndPageNumber
                    
                    # Get Coordinates (Points)
                    # Word (0,0) is Top-Left. PDF (0,0) is usually Bottom-Left.
                    # We need Page Height to flip Y.
                    page_height = doc.PageSetup.PageHeight
                    
                    x = rng.Information(wdHorizontalPositionRelativeToPage)
                    y_word = rng.Information(wdVerticalPositionRelativeToPage)
                    
                    # Flip Y for PDF (assuming 72 DPI / Points)
                    # PDF Y = PageHeight - Word Y
                    y_pdf = page_height - y_word
                    
                    # Adjust for margins if necessary, but Information(RelativeToPage) should be absolute.
                    
                    author = escape_js_string(comment.Author)
                    content = escape_js_string(comment.Range.Text)
                    # Date format might need adjustment, passing as string for now
                    date_str = str(comment.Date) 
                    
                    # Construct JS
                    # Bluebeam/Acrobat JS API: this.addAnnot({ ... })
                    # page is 0-based in JS
                    
                    js_stmt = (
                        f"this.addAnnot({{"
                        f"    page: {page_num - 1},"
                        f"    type: 'Text',"
                        f"    point: [{x}, {y_pdf}],"
                        f"    author: '{author}',"
                        f"    contents: '{content}',"
                        f"    popupOpen: false,"
                        f"    noteIcon: 'Comment'"
                        f"}});"
                    )
                    js_content.append(js_stmt)
                
                js_content.append("console.println('Import complete.');")
                
                with open(js_path, "w", encoding="utf-8") as f:
                    f.write("\n".join(js_content))
                    
                print(f"  Generated: {os.path.basename(js_path)}")
                doc.Close(SaveChanges=False)
                
            except Exception as e:
                print(f"Failed to process {doc_path}: {e}")
                
    finally:
        word.Quit()

if __name__ == "__main__":
    files = [
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\05 05 23.13 10 markup.docx",
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\05 12 00 markup.docx",
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\05 21 00 markup.docx",
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\05 30 00 markup.docx",
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\05 40 00 markup.docx",
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\05 50 14 markup.docx",
        r"C:\Users\Administrator\.gemini\antigravity\scratch\bluebeam-comment-conv\06 17 19 markup.docx"
    ]
    extract_comments_to_js(files)
