# AI-Powered Password Migration

Intelligent password entry migration using OpenAI to automatically fill missing metadata fields.

## Overview

The AI migration feature uses OpenAI's language models to intelligently infer and fill missing metadata fields in your password entries. Instead of manually filling fields like title, URL, username, and category, the AI analyzes your entry keywords and context to suggest appropriate values.

## Installation

The AI migration feature requires the OpenAI SDK:

```bash
pip install openai
```

Set your OpenAI API key:

```bash
export OPENAI_API_KEY='your-api-key-here'
```

Or pass it via the `--api-key` option.

## Usage Workflow

### 1. Generate Review File

Run the AI migration to analyze your entries and generate a review file:

```bash
# Basic usage
onepasswd ai-migrate

# With user context for better inference
onepasswd ai-migrate --context "These are my work accounts for development"

# Use specific model (default: gpt-4o-mini)
onepasswd ai-migrate --model gpt-4o

# Specify output file
onepasswd ai-migrate --output my_review.json
```

**What happens:**
- Reads all entries with missing or incomplete metadata
- Sends metadata (NOT passwords) to OpenAI API
- AI infers missing fields based on keywords and context
- Generates a JSON review file for your approval

**Cost:** Using gpt-4o-mini is very cost-effective (typically <$0.01 per 100 entries)

### 2. Review and Edit

Open the generated review file (JSON format). Each entry looks like:

```json
{
  "keywords": ["github", "work"],
  "missing_fields": ["url", "username", "category"],
  "original": {
    "title": "GitHub"
  },
  "proposed": {
    "title": "GitHub Work Account",
    "url": "https://github.com",
    "username": "user@company.com",
    "category": "Development",
    "description": "GitHub account for work projects",
    "tags": ["development", "git"],
    "confidence": "high",
    "notes": "Inferred from keywords 'github' and 'work'"
  },
  "approved": true,
  "notes": ""
}
```

**Edit as needed:**
- Modify any `proposed` field values
- Set `approved: false` to skip an entry
- Add your own `notes` for future reference

### 3. Preview Changes

Preview what will be applied without making changes:

```bash
onepasswd ai-migrate-apply review.json --dry-run
```

### 4. Apply Changes

Apply the approved changes to your database:

```bash
onepasswd ai-migrate-apply review.json
```

**What happens:**
- Creates automatic backup before applying
- Updates only approved entries
- Updates only non-null fields in `proposed`
- Shows summary of applied/skipped/failed entries

## Command Reference

### `onepasswd ai-migrate`

Generate AI-powered review file with inferred metadata.

**Options:**
- `--context TEXT` - Additional context for AI (e.g., "work accounts", "personal")
- `--model TEXT` - OpenAI model to use (default: gpt-4o-mini)
- `--api-key TEXT` - OpenAI API key (or set OPENAI_API_KEY env var)
- `--batch-size INT` - Entries per API call (default: 20)
- `--output PATH` - Output review file path (default: temp file)

**Examples:**

```bash
# Basic usage
onepasswd ai-migrate

# With context for better results
onepasswd ai-migrate --context "Personal accounts for social media and email"

# Use more powerful model
onepasswd ai-migrate --model gpt-4o

# Process in smaller batches
onepasswd ai-migrate --batch-size 10
```

### `onepasswd ai-migrate-apply`

Apply approved changes from review file.

**Arguments:**
- `REVIEW_FILE` - Path to review JSON file

**Options:**
- `--dry-run` - Preview changes without applying

**Examples:**

```bash
# Preview changes
onepasswd ai-migrate-apply review.json --dry-run

# Apply changes
onepasswd ai-migrate-apply review.json
```

## How It Works

### 1. Data Privacy

- **Passwords are NEVER sent to OpenAI** - only metadata (keywords, title, url, etc.)
- Entry keywords and existing metadata are analyzed
- All password values remain encrypted and local

### 2. AI Inference

The AI analyzes:
- Entry keywords (e.g., "github", "work")
- Existing metadata (if any)
- User-provided context
- Known service patterns (github.com, google.com, etc.)

And infers:
- **title**: User-friendly display name
- **url**: Website URL (with https://)
- **username**: Email or username (if inferable from keywords)
- **category**: Category like "Social", "Email", "Work", "Banking"
- **description**: Brief account description
- **tags**: Relevant tags

### 3. Confidence Levels

Each suggestion includes a confidence level:
- **high**: Very confident (e.g., "github" → https://github.com)
- **medium**: Reasonably confident (e.g., "work-email" → category: "Email")
- **low**: Uncertain inference (manual review recommended)

## Best Practices

### Provide Context

Adding context significantly improves AI inference:

```bash
# Without context - generic inferences
onepasswd ai-migrate

# With context - tailored inferences
onepasswd ai-migrate --context "These are my company accounts for acme.com. My work email is john@acme.com"
```

### Review Before Applying

Always review the generated file:
1. Check high-confidence suggestions (usually accurate)
2. Carefully review low-confidence suggestions
3. Verify URLs are correct
4. Update usernames if AI couldn't infer them

### Use Dry Run First

Preview changes before applying:

```bash
onepasswd ai-migrate-apply review.json --dry-run
```

### Batch Processing

For large databases (100+ entries), use smaller batches to monitor progress:

```bash
onepasswd ai-migrate --batch-size 10
```

## Examples

### Example 1: Social Media Accounts

```bash
# Keywords: ["facebook", "personal"]
onepasswd ai-migrate --context "Personal social media accounts"

# AI infers:
# - title: "Facebook"
# - url: "https://facebook.com"
# - category: "Social"
# - tags: ["social-media", "personal"]
```

### Example 2: Work Accounts

```bash
# Keywords: ["github", "work", "acme"]
onepasswd ai-migrate --context "Work accounts for ACME Corp. My work email is john@acme.com"

# AI infers:
# - title: "GitHub - ACME Corp"
# - url: "https://github.com"
# - username: "john@acme.com"
# - category: "Work"
# - tags: ["development", "work", "acme"]
```

### Example 3: Banking

```bash
# Keywords: ["chase", "bank", "checking"]
onepasswd ai-migrate --context "Personal banking accounts"

# AI infers:
# - title: "Chase Bank - Checking"
# - url: "https://chase.com"
# - category: "Banking"
# - tags: ["finance", "banking"]
```

## Troubleshooting

### OpenAI SDK Not Installed

```
Error: OpenAI SDK not installed
```

**Solution:**
```bash
pip install openai
```

### API Key Missing

```
Error: OpenAI API key required
```

**Solution:**
```bash
export OPENAI_API_KEY='your-api-key-here'
# Or use --api-key option
onepasswd ai-migrate --api-key 'your-api-key-here'
```

### No Entries Need Migration

```
No entries need migration! All entries have complete metadata.
```

This means all your entries already have title, URL, and other metadata filled. You can:
- Add new entries with minimal metadata
- Use the regular `migrate` command for manual migration

### API Rate Limits

If you hit OpenAI rate limits, reduce batch size:

```bash
onepasswd ai-migrate --batch-size 5
```

## Cost Estimation

Using `gpt-4o-mini` (default):
- ~$0.15 per 1M input tokens
- ~$0.60 per 1M output tokens
- Average: ~500 tokens per 20 entries
- **~$0.01 per 100 entries**

For 1000 entries: approximately $0.10 USD

Using `gpt-4o` (more powerful):
- ~10x more expensive than gpt-4o-mini
- Better inference quality for complex cases
- **~$0.10 per 100 entries**

## Comparison: AI vs Manual Migration

| Feature | AI Migration | Manual Migration |
|---------|-------------|------------------|
| Speed | Automatic bulk processing | Entry-by-entry |
| Accuracy | High for common services | 100% accurate |
| User effort | Review only | Fill each field |
| Cost | ~$0.01 per 100 entries | Free |
| Context-aware | Yes (user context) | Manual input |
| Best for | Large databases | Small databases |

## Security & Privacy

### What's Sent to OpenAI

✅ **Sent:**
- Entry keywords (e.g., ["github", "work"])
- Existing metadata (title, url, username, etc.)
- User-provided context

❌ **NOT Sent:**
- Passwords (always encrypted and local)
- Master password
- Any sensitive authentication data

### Data Retention

OpenAI's data retention policy (as of 2024):
- API requests are not used for training by default
- Data may be retained for 30 days for abuse monitoring
- See: https://openai.com/policies/api-data-usage-policies

### Recommendations

1. **Review context carefully** - don't include sensitive info
2. **Use generic context** - "work accounts" instead of "Company X secret project"
3. **Review generated file** - verify no sensitive data leaked
4. **Use local inference** - consider local LLMs for sensitive cases (future feature)

## Future Enhancements

Planned features:
- Local LLM support (Ollama, Llama.cpp)
- Custom inference rules
- Field validation and correction
- Duplicate detection
- URL normalization
- Batch review interface (TUI)

## See Also

- [Migration Documentation](../README.md#migration) - Manual migration guide
- [OpenAI API](https://platform.openai.com/docs) - OpenAI documentation
- [Data Models](../README.md#data-models) - Entry field reference
