#!/usr/bin/env python3
"""Import .apkg/.colpkg Anki cards into Zeitgeist.
Usage: python import-apkg.py <apkg_path> <target_deck_id>

The .apkg must already be extracted (unzip) and collection.anki21b decompressed.
Or point directly to a decompressed SQLite database.
"""

import sqlite3
import json
import time
import random
import shutil
import os
import sys

# ── Config ──────────────────────────────────────────────
ZG_DATA    = '/media/HDD_1TB/Zeitgeist/data/data.json'
STORE_KEY  = 'zeitgeist-anki-v2'

def uid():
    """Generate Zeitgeist-compatible card ID (base36 timestamp + 4 random chars)."""
    t = int(time.time() * 1000)
    chars = '0123456789abcdefghijklmnopqrstuvwxyz'
    b36 = ''
    while t > 0:
        b36 = chars[t % 36] + b36
        t //= 36
    rand = ''.join(random.choice(chars) for _ in range(4))
    return b36 + rand

def import_apkg(db_path, target_deck_id, source_deck_id=None):
    """Import cards from Anki SQLite DB into Zeitgeist deck.
    
    Args:
        db_path: Path to decompressed Anki collection SQLite database
        target_deck_id: Zeitgeist deck ID to import into
        source_deck_id: Anki deck ID to filter (None = import all notes)
    """
    # ── Read source cards ───────────────────────────────
    conn = sqlite3.connect(db_path)
    cur = conn.cursor()
    
    if source_deck_id:
        cur.execute("""
            SELECT n.id, n.guid, n.flds, n.tags, c.did
            FROM notes n
            JOIN cards c ON c.nid = n.id
            WHERE c.did = ?
        """, (source_deck_id,))
    else:
        cur.execute("""
            SELECT n.id, n.guid, n.flds, n.tags, NULL
            FROM notes n
        """)
    
    rows = cur.fetchall()
    conn.close()
    print(f"Found {len(rows)} notes in source database")
    
    # ── Generate Zeitgeist cards ────────────────────────
    new_cards = []
    for row in rows:
        note_id, guid, flds, tags, did = row
        parts = flds.split('\x1f')
        front = parts[0] if len(parts) > 0 else ''
        back = parts[1] if len(parts) > 1 else ''
        
        card = {
            'id': uid(),
            'front': front,
            'back': back,
            'created': int(time.time() * 1000),
            'state': 'new',
            'interval': 0,
            'stability': None,
            'difficulty': None,
            'lastReview': None,
            'dueDate': None,
            'lapses': 0,
            'reviews': 0,
            'learningStep': 0,
            'easeFactor': 2.5,
        }
        new_cards.append(card)
    
    print(f"Generated {len(new_cards)} Zeitgeist cards")
    
    # ── Backup ──────────────────────────────────────────
    ts = time.strftime('%Y-%m-%d_%H%M%S')
    backup_path = f'/tmp/zg-backup-pre-anki-{ts}.json'
    shutil.copy2(ZG_DATA, backup_path)
    print(f"Backup saved: {backup_path}")
    
    # ── Read & update Zeitgeist data ────────────────────
    with open(ZG_DATA, 'r', encoding='utf-8') as f:
        data = json.load(f)
    
    anki_raw = data.get(STORE_KEY, '{"decks":{}}')
    anki = json.loads(anki_raw)
    
    if target_deck_id not in anki.get('decks', {}):
        print(f"ERROR: Deck {target_deck_id} not found in Zeitgeist!")
        print(f"Available decks: {list(anki.get('decks', {}).keys())}")
        sys.exit(1)
    
    deck = anki['decks'][target_deck_id]
    existing = deck.get('cards', [])
    print(f"Deck '{deck['name']}' had {len(existing)} cards before import")
    
    deck['cards'] = existing + new_cards
    print(f"Deck now has {len(deck['cards'])} cards")
    
    data[STORE_KEY] = json.dumps(anki, ensure_ascii=False)
    
    # ── Write to tmp, then move with sudo ───────────────
    tmp_path = '/tmp/zg-data-new.json'
    with open(tmp_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False)
    
    print(f"\nNow run: sudo mv {tmp_path} {ZG_DATA}")
    print(f"✅ {len(new_cards)} cards ready for import into '{deck['name']}'")
    
    # ── Show sample ─────────────────────────────────────
    print("\n── Sample cards ──")
    for c in new_cards[:3]:
        print(f"  Front: {c['front'][:80]}")
        print(f"  Back:  {c['back'][:80]}")
        print()
    
    return tmp_path

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: python import-apkg.py <db_path> <target_deck_id> [source_deck_id]")
        print("Example: python import-apkg.py /tmp/collection_decompressed.anki21 mq0izjiyplw9 1765743870788")
        sys.exit(1)
    
    db_path = sys.argv[1]
    target_deck_id = sys.argv[2]
    source_deck_id = int(sys.argv[3]) if len(sys.argv) > 3 else None
    
    import_apkg(db_path, target_deck_id, source_deck_id)
