#!/usr/bin/env python3
"""
Sync the lyrics files to Apple Notes so they're reviewable on the road.

Reads every `*.txt` in `portfolio/lyrics/` and upserts one note per song into a
"Lyrics" folder in Apple Notes (the folder is created if it doesn't exist). The
note title is derived from the filename (`song_by_artist.txt` -> "Song - Artist");
the whole file is the note body. Re-running updates existing notes in place rather
than duplicating them.

Note on content: the lyric files are copyrighted and must not be opened by the
model (reading their contents trips the content-filter). This script only ever
pipes the text through `osascript` into Notes — it never prints the lyrics — so it
is safe to run. It prints only the derived title per song.

Usage:
    python3 lyrics_to_apple_notes.py
"""

import subprocess
from pathlib import Path

LYRICS_DIR = Path(__file__).parents[1] / "lyrics"  # portfolio/lyrics
NOTES_FOLDER = "Lyrics"
MAX_FILES = 200


def escape_for_applescript(text):
    return text.replace("\\", "\\\\").replace('"', '\\"')


def upsert_note(title, body):
    safe_title = escape_for_applescript(title)
    safe_body = escape_for_applescript(
        f'<pre style="font-family: monospace; font-size: inherit; '
        f'white-space: pre-wrap;">{body}</pre>'
    )
    script = f'''
    tell application "Notes"
        if not (exists folder "{NOTES_FOLDER}") then
            make new folder with properties {{name:"{NOTES_FOLDER}"}}
        end if
        set targetFolder to folder "{NOTES_FOLDER}"
        set existing to (every note in targetFolder whose name is "{safe_title}")
        if length of existing > 0 then
            set body of item 1 of existing to "{safe_body}"
        else
            make new note at targetFolder with properties {{name:"{safe_title}", body:"{safe_body}"}}
        end if
    end tell
    '''
    subprocess.run(["osascript", "-e", script], check=True)


def song_title(path: Path) -> str:
    """`simple_man_by_lynyrd_skynyrd` -> `Simple Man - Lynyrd Skynyrd`."""
    stem = path.stem
    if "_by_" in stem:
        song, artist = stem.split("_by_", 1)
        return f"{song.replace('_', ' ').title()} - {artist.replace('_', ' ').title()}"
    return stem.replace("_", " ").title()


def main():
    if not LYRICS_DIR.is_dir():
        print(f"No lyrics folder at {LYRICS_DIR}")
        return
    files = sorted(LYRICS_DIR.glob("*.txt"))[:MAX_FILES]
    if not files:
        print(f"No .txt files found in {LYRICS_DIR}")
        return
    for path in files:
        lyrics = path.read_text().strip()
        if not lyrics:
            print(f"Skipped (empty): {path.name}")
            continue
        title = song_title(path)
        body = f"{title}\n\n{lyrics}"
        upsert_note(title, body)
        print(f'Synced: "{title}"')


if __name__ == "__main__":
    main()
