import subprocess
import re
import os

output_dir = os.path.expanduser("~/Desktop/Alex Wiki/rocky-mountain-tattoo/notes")

def export_note_contains(search_term, filename):
    """Export a note whose name contains the given term (case-insensitive)."""
    escaped = search_term.replace('\\', '\\\\').replace('"', '\\"')
    
    script = f'''
    tell application "Notes"
        repeat with n in every note
            set noteName to name of n
            set lowerName to do shell script "echo " & quoted form of noteName & " | tr '[:upper:]' '[:lower:]'"
            if lowerName contains "{escaped}" then
                return plaintext of n
            end if
        end repeat
        return "___NOTE_NOT_FOUND___"
    end tell
    '''
    
    try:
        result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True, timeout=30)
        content = result.stdout.strip()
        if content and content != "___NOTE_NOT_FOUND___":
            filepath = os.path.join(output_dir, filename)
            with open(filepath, 'w') as f:
                f.write(content)
            return True
        return False
    except Exception as e:
        print(f"  ERROR: {e}")
        return False

remaining = [
    ("rmt ai", "training plan", "rmt-ai-training-plan.md"),
    ("rocky mountain tattoo", "locations", "rmt-locations.md"),
    ("rocky mountain tattoo studio", "ai studio website", "rmt-studio-ai-website-agentic.md"),
    ("tattoo ai os", "one instance", "tattoo-ai-os-instance.md"),
    ("client acquisition", "engine", "client-acquisition-engine.md"),
    ("copywriting", None, "copywriting.md"),
    ("tasks", "google maps", "tasks-google-maps-business.md"),
    ("context", "station rental", "context-not-station-rental.md"),
    ("victor", "marketing", "victor-ziggy-resident-artists.md"),
]

for terms in remaining:
    filename = terms[-1]
    # Use the combined search
    if len(terms) == 3:
        t1, t2, fname = terms
        escaped1 = t1.replace('"', '\\"')
        escaped2 = t2.replace('"', '\\"') if t2 else None
        
        if escaped2:
            condition = f'lowerName contains "{escaped1}" and lowerName contains "{escaped2}"'
        else:
            condition = f'lowerName starts with "{escaped1}"'
        
        script = f'''
        tell application "Notes"
            repeat with n in every note
                set noteName to name of n
                set lowerName to do shell script "echo " & quoted form of noteName & " | tr '[:upper:]' '[:lower:]'"
                if {condition} then
                    return plaintext of n
                end if
            end repeat
            return "___NOTE_NOT_FOUND___"
        end tell
        '''
        
        try:
            result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True, timeout=30)
            content = result.stdout.strip()
            if content and content != "___NOTE_NOT_FOUND___":
                filepath = os.path.join(output_dir, fname)
                with open(filepath, 'w') as f:
                    f.write(content)
                print(f"OK: {fname}")
            else:
                print(f"MISS: {fname}")
        except Exception as e:
            print(f"ERROR: {fname} - {e}")

