"""Import command - fetch notes from Anki and save as YAML files."""

import logging
from typing import Optional
from datetime import datetime

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

logger = logging.getLogger(__name__)


def import_notes(output_dir: str = "notes") -> None:
    """Import all notes from Anki and save as YAML files.
    
    Args:
        output_dir: Directory to save YAML files to
        
    Raises:
        AnkiConnectError: If connection to Anki fails
    """
    client = AnkiClient()
    file_manager = FileManager(output_dir)
    
    try:
        # Fetch all note IDs
        note_ids = client.get_all_note_ids()
        
        if not note_ids:
            logger.info("No notes found in Anki")
            print("✓ No notes to import")
            return
        
        # Fetch note details in batches (Anki Connect has limits)
        batch_size = 100
        total_imported = 0
        errors = 0
        
        print(f"Importing {len(note_ids)} notes from Anki...")
        
        for i in range(0, len(note_ids), batch_size):
            batch = note_ids[i:i + batch_size]
            
            try:
                notes_info = client.get_notes_info(batch)
                
                for note_info in notes_info:
                    try:
                        # Extract note data
                        note_id = note_info['noteId']
                        model_name = note_info['modelName']
                        tags = note_info.get('tags', [])
                        fields = note_info.get('fields', {})
                        
                        # Convert fields dict to simple string dict
                        # Anki returns fields with 'value' and 'order' keys
                        field_values = {}
                        if isinstance(fields, dict):
                            for field_name, field_data in fields.items():
                                if isinstance(field_data, dict):
                                    field_values[field_name] = field_data.get('value', '')
                                else:
                                    field_values[field_name] = str(field_data)
                        
                        # Create Note object
                        note = Note(
                            id=note_id,
                            type=model_name,
                            tags=tags,
                            fields=field_values,
                            created=datetime.now(),  # Anki doesn't expose creation time easily
                            modified=datetime.now(),
                        )
                        
                        # Save to YAML
                        file_manager.save_note(note)
                        total_imported += 1
                        
                    except Exception as e:
                        logger.error(f"Failed to import note {note_info.get('noteId')}: {e}")
                        errors += 1
                
            except Exception as e:
                logger.error(f"Failed to fetch batch: {e}")
                errors += len(batch)
        
        # Print summary
        print(f"✓ Imported {total_imported} notes to {output_dir}/")
        if errors > 0:
            print(f"⚠ {errors} notes failed to import")
        
    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 import: {e}")
        print(f"✗ Unexpected error: {e}")
        raise
