"""Export command - sync YAML files back to Anki."""

import logging
from typing import Tuple, List

from ..anki_client import AnkiClient, AnkiConnectError
from ..file_manager import FileManager
from ..models import Note

logger = logging.getLogger(__name__)


def export_notes(input_dir: str = "notes", deck_name: str = "Default") -> None:
    """Export/sync notes from YAML files back to Anki.
    
    Args:
        input_dir: Directory containing YAML files
        deck_name: Deck to add new notes to (for notes without existing IDs)
        
    Raises:
        AnkiConnectError: If connection to Anki fails
    """
    client = AnkiClient()
    file_manager = FileManager(input_dir)
    
    try:
        # Load all notes from YAML files
        notes = file_manager.get_all_notes()
        
        if not notes:
            logger.info("No YAML files found to export")
            print("✓ No notes to export")
            return
        
        updated_count = 0
        created_count = 0
        errors = 0
        failed_notes = []
        
        print(f"Syncing {len(notes)} notes to Anki...")
        
        for note in notes:
            try:
                if client.note_exists(note.id):
                    # Update existing note
                    client.update_note(
                        note.id,
                        fields=note.fields,
                        tags=note.tags
                    )
                    updated_count += 1
                    logger.debug(f"Updated note {note.id}")
                else:
                    # Create new note
                    new_note_data = {
                        "deckName": deck_name,
                        "modelName": note.type,
                        "fields": note.fields,
                        "tags": note.tags
                    }
                    
                    new_id = client.add_note(new_note_data)
                    
                    # Find the YAML file for this note and update its ID
                    yaml_files = file_manager.get_all_yaml_files()
                    for yaml_file in yaml_files:
                        loaded_note = file_manager.load_note(yaml_file)
                        if loaded_note and loaded_note.id == note.id:
                            if file_manager.update_note_id_in_file(yaml_file, new_id):
                                logger.debug(f"Updated YAML file {yaml_file} with new ID {new_id}")
                            break
                    
                    created_count += 1
                    logger.debug(f"Created note with ID {new_id}")
                    
            except AnkiConnectError as e:
                logger.error(f"Failed to sync note {note.id}: {e}")
                failed_notes.append((note.id, str(e)))
                errors += 1
            except Exception as e:
                logger.error(f"Unexpected error syncing note {note.id}: {e}")
                failed_notes.append((note.id, str(e)))
                errors += 1
        
        # Print summary
        print(f"✓ Synced {len(notes)} notes")
        print(f"  - Updated: {updated_count}")
        print(f"  - Created: {created_count}")
        
        if errors > 0:
            print(f"⚠ {errors} notes failed to sync:")
            for note_id, error in failed_notes:
                print(f"    - Note {note_id}: {error}")
        
    except AnkiConnectError as e:
        logger.error(f"Anki Connect error: {e}")
        print(f"✗ Error: {e}")
        raise
    except Exception as e:
        logger.error(f"Unexpected error during export: {e}")
        print(f"✗ Unexpected error: {e}")
        raise
