#!/usr/bin/env python3
"""Generate src/data/scans.json for the astro_vedabase 'Original Edition Scans'
page. URLs are built with the same sanitize() rule used by upload_scans_r2.sh,
so they match the R2 keys served at https://vedabase.cc/downloads/scans/...
Only originals/ is published; improved/ stays in R2 unlinked."""
import os, re, json, glob

SRC = os.path.expanduser('~/git_projects/scan_vedabase/originals')
OUT = os.path.expanduser('~/git_projects/astro_vedabase/src/data/scans.json')
BASEURL = '/downloads/scans/originals'

def sanitize(name):
    return re.sub(r'[(),]', '', name.replace(' ', '-'))

def mb(path):
    return round(os.path.getsize(path) / 1048576, 1)

# Hand-titled named books (top level of originals/).
TITLES = {
 '1972_Perfection_of_Yoga_2008_Original.pdf': 'The Perfection of Yoga',
 '1973_Elevation_to_Krsna_Consciousness.pdf': 'Elevation to Kṛṣṇa Consciousness (1973)',
 '1973_Raja-Vidya_The_King_of_Knowledge.pdf': 'Rāja-Vidyā: The King of Knowledge (1973)',
 'Beyond_Birth_and_Death-Original_1974_edition_scan.pdf': 'Beyond Birth and Death (1974)',
 'Easy_Journey_to_Other_Planets-Original_India_Edition_SCAN.pdf': 'Easy Journey to Other Planets (Original India edition)',
 'Easy-Journey-to-Other-Planets-1972-krishnaorg-SCAN.pdf': 'Easy Journey to Other Planets (1972)',
 'KRSNA Consciousness - The Topmost Yoga System - Original 1970 edition Scan.pdf': 'Kṛṣṇa Consciousness: The Topmost Yoga System (1970)',
 'KRSNA-the-Reservoir-of-Pleasure-1970.pdf': 'Kṛṣṇa, the Reservoir of Pleasure (1970)',
 'Light_of_the_Bhagavata-1984_first_edition_SCAN.pdf': 'Light of the Bhāgavata (1984 first edition)',
 'On_the_Way_to_Krsna-1973_book_SCAN.pdf': 'On the Way to Kṛṣṇa (1973)',
 'Perfect_Questions_Perfect_Answers-Original_1977_Edition-SCAN.pdf': 'Perfect Questions, Perfect Answers (1977)',
 'Science-of-Self-Realization-1977.pdf': 'The Science of Self-Realization (1977)',
 'Sri-Isopanisad-scans-of-original-1969-edition.pdf': 'Śrī Īśopaniṣad (1969 first edition)',
 'Teachings_of_Lord_Chaitanya-1968_first_edition-SCAN.pdf': 'Teachings of Lord Caitanya (1968 first edition)',
 'Teachings_of_Lord_Kapila-SCAN.pdf': 'Teachings of Lord Kapila',
 'Teachings_of_Queen_Kunti-SCAN.pdf': 'Teachings of Queen Kuntī',
 'The_Nectar_of_Devotion-1970_ISKCON_Press_edition-Hardcover-SCAN.pdf': 'The Nectar of Devotion (1970)',
 'The_Nectar_of_Instruction-Original_1976_SCAN.pdf': 'The Nectar of Instruction (1976)',
 'The-Path-of-Perfection-SCAN.pdf': 'The Path of Perfection',
 'Transcendental_Teachings_of_Caitanya_Mahaprabhu.pdf': 'Transcendental Teachings of Caitanya Mahāprabhu',
 'Transcendental_Teachings_of_Prahlad_Maharaj-Original_book-SCAN.pdf': 'Transcendental Teachings of Prahlāda Mahārāja',
 'KRSNA_Book_Vol.1_1970_ISKCON_Press_edition_SCAN.pdf': 'Kṛṣṇa Book, Volume 1 (1970 ISKCON Press)',
 'KRSNA_Book_Vol.2_1970_ISKCON_Press_edition_SCAN.pdf': 'Kṛṣṇa Book, Volume 2 (1970 ISKCON Press)',
}
LILA = {'adi': 'Ādi-līlā', 'mad': 'Madhya-līlā', 'ant': 'Antya-līlā'}


def entry(path, urlbase):
    name = os.path.basename(path)
    return {'title': None, 'url': f'{urlbase}/{sanitize(name)}', 'mb': mb(path)}


def main():
    groups = []

    # Śrīmad-Bhāgavatam — original canto set
    sb = []
    for p in sorted(glob.glob(f'{SRC}/sb_original_prabhupada/SB*.pdf') +
                    glob.glob(f'{SRC}/sb_original_prabhupada/sb*.pdf')):
        m = re.search(r'[Ss][Bb](\d+)\.(\d+)', os.path.basename(p))
        canto, part = (int(m.group(1)), int(m.group(2))) if m else (99, 0)
        e = {'title': f'Canto {canto}, Part {part}', 'url': f'{BASEURL}/sb/{os.path.basename(p)}',
             'mb': mb(p), '_sort': (canto, part)}
        sb.append(e)
    sb.sort(key=lambda x: x['_sort'])
    for e in sb:
        del e['_sort']
    groups.append({'group': 'Śrīmad-Bhāgavatam — original edition (Cantos 1–10)', 'items': sb})

    # Caitanya-caritāmṛta — 1975 multi-volume
    cc = []
    for p in sorted(glob.glob(f'{SRC}/adi*.pdf') + glob.glob(f'{SRC}/mad*.pdf') + glob.glob(f'{SRC}/ant*.pdf')):
        m = re.match(r'(adi|mad|ant)(\d+)', os.path.basename(p))
        e = {'title': f'{LILA[m.group(1)]}, Volume {int(m.group(2))}', 'url': f'{BASEURL}/{sanitize(os.path.basename(p))}',
             'mb': mb(p), '_sort': (['adi', 'mad', 'ant'].index(m.group(1)), int(m.group(2)))}
        cc.append(e)
    cc.sort(key=lambda x: x['_sort'])
    for e in cc:
        del e['_sort']
    groups.append({'group': 'Śrī Caitanya-caritāmṛta — 1975 edition', 'items': cc})

    # Other books (everything named in TITLES, excluding CC/SB handled above)
    other = []
    for p in sorted(glob.glob(f'{SRC}/*.pdf')):
        name = os.path.basename(p)
        if name in TITLES:
            other.append({'title': TITLES[name], 'url': f'{BASEURL}/{sanitize(name)}', 'mb': mb(p)})
    other.sort(key=lambda x: x['title'])
    groups.append({'group': 'Other Books', 'items': other})

    os.makedirs(os.path.dirname(OUT), exist_ok=True)
    json.dump({'groups': groups}, open(OUT, 'w'), ensure_ascii=False, indent=1)
    total = sum(len(g['items']) for g in groups)
    print(f'wrote {OUT}: {total} PDFs in {len(groups)} groups')


if __name__ == '__main__':
    main()
