#!/usr/bin/env python3
"""Backup current drafts and re-draft with new prompts."""
import os
import sys
sys.path.insert(0, '/root/alwaysbeselling')

from dotenv import load_dotenv
load_dotenv('/root/alwaysbeselling/.env')

from state.backlog import load_backlog, save_backlog
from capabilities.drafting import draft_touch
import time

backlog = load_backlog()

# Backup current drafts to old_draft_* fields
print("Backing up current drafts...")
for lead in backlog:
    if lead.get('draft_body'):
        lead['old_draft_subject'] = lead.get('draft_subject')
        lead['old_draft_body'] = lead.get('draft_body')
        lead['old_draft_anchor'] = lead.get('draft_anchor')
        lead['old_draft_scenario'] = lead.get('draft_scenario')
        lead['old_draft_model'] = lead.get('draft_model')
        lead['old_drafted_at'] = lead.get('drafted_at')

save_backlog(backlog)
print("Backed up.")

# Now re-draft all
drafted_leads = [l for l in backlog if l.get('old_draft_body')]
print(f"\nRe-drafting {len(drafted_leads)} leads...")

success = 0
errors = 0
for i, lead in enumerate(drafted_leads, 1):
    name = lead.get('name', 'Unknown')[:35]
    lead_id = lead.get('id')
    temporal = lead.get('temporal_category', 'unknown')
    
    print(f"[{i}/{len(drafted_leads)}] {name} ({temporal})")
    try:
        result = draft_touch(lead_id)
        print(f"  New subject: {result.get('subject', 'N/A')[:50]}")
        success += 1
    except Exception as e:
        print(f"  ERROR: {e}")
        errors += 1
    
    time.sleep(1.5)  # Rate limit

print(f"\nDone. Success: {success}, Errors: {errors}")
SCRIPT