import subprocess
import re
import os

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

def clean_filename(title):
    clean = title[:80]
    clean = re.sub(r'[^\w\s-]', '', clean)
    clean = re.sub(r'\s+', '-', clean.strip())
    clean = clean.lower()
    clean = re.sub(r'-+', '-', clean)
    clean = clean.strip('-')
    if not clean:
        clean = "untitled"
    return clean[:80] + ".md"

def export_note_by_prefix(prefix, filename):
    """Export a note whose name starts with the given prefix."""
    # Escape for AppleScript
    escaped = prefix.replace('\\', '\\\\').replace('"', '\\"')
    
    script = f'''
    tell application "Notes"
        repeat with n in every note
            set noteName to name of n
            if noteName starts with "{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
        else:
            return False
    except Exception as e:
        print(f"  ERROR: {e}")
        return False

# Map of search prefix -> filename
notes = [
    ("TattooClaw", "tattooclaw-ai-studio-management.md"),
    ("# Square Setup Guide for Rocky Mountain", "square-setup-guide-rmt.md"),
    ("RMT AI-NATIVE CONTEXT SYSTEM BUILD", "rmt-ai-native-context-system-build.md"),
    ("system ontology / SSOT excavations", "system-ontology-ssot-rmt.md"),
    ("RMT WEBAPP", "rmt-webapp-locations.md"),
    ("IMAGES PROMPT BOOT", "rmt-hyper-realism-protocol.md"),
    ("rmt gmail", "rmt-gmail-passwords.md"),
    ("RMT VANCITY", "rmt-vancity-vancouver-launch.md"),
    ("website context graph", "rmt-website-context-graph.md"),
    ("## RMT - Vancouver: Revenue Streams", "rmt-vancouver-revenue-streams.md"),
    ("# RMT Knowledge Graph", "rmt-knowledge-graph-query-cheats.md"),
    ("RMT AUTOMATION", "rmt-automation.md"),
    ("RMT AI    [ TRAINING", "rmt-ai-training-plan.md"),
    ("<!-- RMT Lite Artist Price Calculator", "rmt-lite-artist-price-calculator.md"),
    ("To-Do List (Kelowna", "todo-list-kelowna.md"),
    ("BOOKIN FORM", "booking-form.md"),
    ("RMT SETUP", "rmt-setup-foundation.md"),
    ("532 Bernard Ave", "532-bernard-ave-kelowna.md"),
    ("ROCKY MOUNTAIN TATTOO  [ LOCATIONS ]", "rmt-locations.md"),
    ("ROCKY MOUNTAIN TATTOO: master context", "rmt-master-context-doc.md"),
    ("AI tattoo studio website RMT", "ai-tattoo-studio-website-rmt.md"),
    ("RMT  PASSWORDS", "rmt-passwords.md"),
    ("Rocky Mountain Tattoo Studio  AI Studio", "rmt-studio-ai-website-agentic.md"),
    ("2025  ROCKY MOUNTAIN TATTOO", "2025-rocky-mountain-tattoo.md"),
    ("Color codes RMT", "color-codes-rmt.md"),
    ("TATTOO AI OS      I will give you one instance", "tattoo-ai-os-instance.md"),
    ("Square - cash transfer", "square-cash-transfer-appointments.md"),
    ("consent forms / boxes", "consent-forms-supplies.md"),
    ("SEO AND META", "seo-and-meta-descriptions.md"),
    ("3 pillars", "3-pillars-apprentice.md"),
    ("AGENT IDEAS ON WIX", "agent-ideas-on-wix.md"),
    ("operational business plan", "operational-business-plan.md"),
    ("CLIENT ACQUISITION  ENGINE", "client-acquisition-engine.md"),
    ("BLOG IDEAS", "blog-ideas.md"),
    ("COPYWRITING     {", "copywriting.md"),
    ("Strategist Mode", "strategist-mode-google-maps.md"),
    ("UNIFIED CSV FORMAT", "unified-csv-format.md"),
    ("SITE STRUCTURE", "site-structure.md"),
    ("BRAND FOUNDATION", "brand-foundation.md"),
    ("Pre-launch CMS lint", "pre-launch-cms-lint.md"),
    ("TATTOO AI OS", "tattoo-ai-os.md"),
    ("info@rockymountaintattoovancouver", "rmt-vancouver-emails.md"),
    ("we will build a backend for a 4 location", "rmt-backend-4-locations.md"),
    ("Uzdevumi", "uzdevumi-tasks.md"),
    ("taski:", "taski-tasks.md"),
    ("ask - REVIEWS", "reviews-marketing-laser.md"),
    ("ARTISTS ONBOARDING PDF", "artists-onboarding-pdf.md"),
    ("setup artists booklet", "setup-artists-booklet.md"),
    ("MIGRATION", "migration.md"),
    ("TASKS     google maps", "tasks-google-maps-business.md"),
    ("CONTEXT   we are not in studio station", "context-not-station-rental.md"),
    ("Victor  Marketing and Marketing Strategy", "victor-ziggy-resident-artists.md"),
]

success = 0
failed = []

for i, (prefix, filename) in enumerate(notes):
    print(f"[{i+1}/{len(notes)}] {filename}...", end=" ", flush=True)
    if export_note_by_prefix(prefix, filename):
        print("OK")
        success += 1
    else:
        print("MISS")
        failed.append((prefix, filename))

print(f"\n=== DONE: {success}/{len(notes)} exported ===")
if failed:
    print("Failed:")
    for p, f in failed:
        print(f"  - {p} -> {f}")
