import os
import argparse
import logging
from datetime import datetime
import shutil
import glob
from typing import List, Tuple, Optional
from pathlib import Path

from anki_generator.clients.llm import AnthropicClient
from anki_generator.clients.unsplash import UnsplashClient
from anki_generator.card_generator import CardGenerator, GermanDeckPackage

logger = logging.getLogger(__name__)

def read_word_list(file_path: str) -> List[Tuple[str, str]]:
    """Read word list from file"""
    words = []
    logger.info("Reading file: %s", file_path)
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            logger.debug("Processing line: %s", line.strip())
            # Expected format: word,source
            word, source = line.strip().split(',', 1)
            words.append((word.strip(), source.strip()))
            logger.debug("Added word: %s with source: %s", word.strip(), source.strip())
    return words

def main():
    parser = argparse.ArgumentParser(description='Generate Anki cards for German vocabulary')
    parser.add_argument('--input', required=True, help='Input file with words and sources')
    parser.add_argument('--output', help='Output file name (optional)')
    parser.add_argument('--deck-name', default='German Vocabulary', help='Name of the Anki deck')
    
    args = parser.parse_args()

    logger.info("Starting Anki card generation")

    try:
        llm_client = AnthropicClient()
        unsplash_client = UnsplashClient()

        generator = CardGenerator(llm_client, unsplash_client)

        words = read_word_list(args.input)

        deck, media_files = generator.create_deck(words, args.deck_name)

        output_dir = "output"
        os.makedirs(output_dir, exist_ok=True)

        if not args.output:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_file = os.path.join(output_dir, f"german_vocab_{timestamp}.apkg")
        else:
            output_file = os.path.join(output_dir, args.output)

        media_paths = []
        for media_file in media_files:
            media_path = os.path.join(output_dir, os.path.basename(media_file))
            if os.path.exists(media_file) and media_file != media_path:
                shutil.copy2(media_file, media_path)
            media_paths.append(media_path)

        package = GermanDeckPackage(deck, media_paths)
        package.write_to_file(output_file)
        logger.info("Deck and media files saved in: %s", output_dir)

    except Exception as e:
        logger.error("Error: %s", str(e))
        raise

if __name__ == "__main__":
    main()
