"""
Migration utility for upgrading old entries with rich metadata.
"""
import click
from onepasswd.client import get_db, from_ctx, get_passwd
from onepasswd import crypto
import time


@click.command()
@click.option('-c', '--config', 'config', required=True, help='config path')
@click.option('-i', '--interactive', 'interactive', is_flag=True, 
              help='interactive mode: prompt for each entry')
@click.option('--dry-run', 'dry_run', is_flag=True, help='preview changes without saving')
@click.pass_context
def migrate(ctx, config, interactive, dry_run):
    """
    Migrate old entries to v2 format with rich metadata.
    
    This tool helps you:
    - Upgrade entries to version 2 format
    - Add missing metadata (title, url, username, etc.)
    - Auto-infer title and URL from keywords
    """
    from onepasswd.config import Config
    from onepasswd.models import PasswordEntry
    
    ctx.ensure_object(dict)
    ctx.obj['config_path'] = config
    cfg = Config(config)
    ctx.obj['config'] = cfg
    
    db = get_db(ctx)
    
    click.echo("=" * 60)
    click.echo("onepasswd Migration Tool")
    click.echo("=" * 60)
    
    # Get master password
    passwd = get_passwd(ctx, promt='master password', from_clipboard=False)
    if not crypto.auth(cfg['auth_info'], passwd):
        click.echo("✗ Password wrong")
        exit(1)
    
    # Collect all entries
    entries_to_migrate = []
    entries_already_v2 = []
    
    for key, data in db.db.items():
        if 'deleted' in data:
            continue
        
        version = data.get('version', 1)
        entry = PasswordEntry.from_dict(data)
        
        if version == 1 or not (entry.title or entry.url or entry.username):
            entries_to_migrate.append(entry)
        else:
            entries_already_v2.append(entry)
    
    click.echo(f"\nFound {len(entries_to_migrate)} entries to migrate")
    click.echo(f"Found {len(entries_already_v2)} entries already in v2 format")
    
    if not entries_to_migrate:
        click.echo("\n✓ All entries are already up to date!")
        return
    
    if dry_run:
        click.echo("\n📋 DRY RUN MODE - No changes will be saved\n")
    
    click.echo("\n" + "=" * 60)
    
    updated_count = 0
    
    for idx, entry in enumerate(entries_to_migrate, 1):
        click.echo(f"\n[{idx}/{len(entries_to_migrate)}]")
        click.echo(f"Keywords: {' '.join(entry.entries)}")
        
        # Infer metadata
        inferred_title, inferred_url = entry.infer_metadata()
        
        if not interactive:
            # Auto mode: use inferred values
            title = entry.title or inferred_title
            url = entry.url or inferred_url
            username = entry.username or ""
            description = entry.description or ""
            category = entry.category or ""
            tags = entry.tags or []
            
            click.echo(f"  Auto-inferred title: {title}")
            click.echo(f"  Auto-inferred URL: {url}")
        else:
            # Interactive mode: prompt for each field
            click.echo(f"  Inferred title: {inferred_title}")
            click.echo(f"  Inferred URL: {inferred_url}")
            
            title = click.prompt('Title', default=inferred_title, show_default=True)
            url = click.prompt('URL', default=inferred_url, show_default=True)
            username = click.prompt('Username/Email', default='', show_default=False)
            description = click.prompt('Description', default='', show_default=False)
            category = click.prompt('Category', default='', show_default=False)
            tags_str = click.prompt('Tags (comma-separated)', default='', show_default=False)
            tags = [t.strip() for t in tags_str.split(',') if t.strip()]
        
        # Update entry
        update_fields = {}
        if title:
            update_fields['title'] = title
        if url:
            update_fields['url'] = url
        if username:
            update_fields['username'] = username
        if description:
            update_fields['description'] = description
        if category:
            update_fields['category'] = category
        if tags:
            update_fields['tags'] = tags
        
        if not dry_run and update_fields:
            try:
                db.update_item(tuple(entry.entries), **update_fields)
                updated_count += 1
                click.echo("  ✓ Updated")
            except Exception as e:
                click.echo(f"  ✗ Error: {e}")
        elif dry_run:
            click.echo("  ○ Would update (dry run)")
            updated_count += 1
        
        # Ask to continue in interactive mode
        if interactive and idx < len(entries_to_migrate):
            if not click.confirm("\nContinue to next entry?", default=True):
                break
    
    click.echo("\n" + "=" * 60)
    if dry_run:
        click.echo(f"✓ Dry run complete: {updated_count} entries would be updated")
    else:
        click.echo(f"✓ Migration complete: {updated_count} entries updated")
    click.echo("=" * 60)


if __name__ == '__main__':
    migrate()
