#!/usr/bin/env python3
"""
Rename special directories (manual_*, PPV, import_*) to use date format.
For multiple posts on same date, use suffixes: YYYY-MM-DD, YYYY-MM-DD_2, etc.
"""

import os
import sys
from pathlib import Path
from collections import defaultdict

sys.path.insert(0, '/opt/media-downloader')
from modules.unified_database import UnifiedDatabase


def main():
    import argparse
    parser = argparse.ArgumentParser(description='Fix special directory names')
    parser.add_argument('--dry-run', action='store_true', help='Show changes without making them')
    args = parser.parse_args()

    db = UnifiedDatabase()
    base_path = Path('/opt/immich/paid/fansly/puffinasmr')

    stats = {'renamed': 0, 'db_updated': 0, 'errors': 0}

    # Find all special directories grouped by date
    date_dirs = defaultdict(list)

    for date_dir in base_path.iterdir():
        if not date_dir.is_dir():
            continue
        date_str = date_dir.name

        for post_dir in date_dir.iterdir():
            if not post_dir.is_dir():
                continue
            name = post_dir.name
            # Check if it's a special directory (not a numeric post_id)
            if name.startswith('manual_') or name.startswith('import_') or name == 'PPV':
                date_dirs[date_str].append(post_dir)

    # Process each date
    for date_str, dirs in sorted(date_dirs.items()):
        # Check if a date-named directory already exists
        existing_date_dir = base_path / date_str / date_str
        suffix = 1
        if existing_date_dir.exists():
            # Find next available suffix
            while (base_path / date_str / f"{date_str}_{suffix + 1}").exists():
                suffix += 1
            suffix += 1

        for old_dir in sorted(dirs, key=lambda d: d.name):
            # Determine new name
            if suffix == 1:
                new_name = date_str
            else:
                new_name = f"{date_str}_{suffix}"

            new_dir = old_dir.parent / new_name

            # Skip if target exists
            if new_dir.exists():
                print(f"  SKIP (exists): {old_dir} -> {new_dir}")
                suffix += 1
                continue

            print(f"  {old_dir.name} -> {new_name}")

            if not args.dry_run:
                try:
                    old_dir.rename(new_dir)
                    stats['renamed'] += 1

                    # Update database paths
                    with db.get_connection(for_write=True) as conn:
                        cursor = conn.cursor()
                        cursor.execute("""
                            UPDATE paid_content_attachments
                            SET local_path = REPLACE(local_path, ?, ?)
                            WHERE local_path LIKE ?
                        """, (str(old_dir), str(new_dir), f"%{old_dir}%"))
                        stats['db_updated'] += cursor.rowcount

                        # Also update posts table if post_id matches the old dir name
                        old_name = old_dir.name
                        if old_name.startswith('manual_'):
                            cursor.execute("""
                                UPDATE paid_content_posts
                                SET post_id = ?
                                WHERE post_id = ?
                            """, (new_name, old_name))

                        conn.commit()
                except Exception as e:
                    print(f"    ERROR: {e}")
                    stats['errors'] += 1

            suffix += 1

    print("\n" + "=" * 50)
    print("SUMMARY")
    print("=" * 50)
    print(f"Directories renamed: {stats['renamed']}")
    print(f"DB records updated:  {stats['db_updated']}")
    print(f"Errors:              {stats['errors']}")

    if args.dry_run:
        print("\n(Dry run - no changes made)")


if __name__ == '__main__':
    main()
