"""
Undo the project consolidation - restore original names from window_title
"""
from sqlalchemy import create_engine, text
import os
import re

DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:asdf1234@localhost:5432/timesheet")
engine = create_engine(DATABASE_URL)

print("\n" + "="*80)
print("UNDOING CONSOLIDATION - This will take a while...")
print("="*80 + "\n")

with engine.connect() as conn:
    # For each consolidated project, re-extract original names from window_title
    consolidated_projects = [
        'mahindraManulifeDistributor',
        'mahindraCMS',
        'mahindraManulifeRetail',
        'timesheet_new',
        'laravel_vue_starter',
        'temp-copy'
    ]

    for project in consolidated_projects:
        print(f"\nProcessing: {project}")
        print("-" * 80)

        # Get records for this consolidated project
        result = conn.execute(text("""
            SELECT id, window_title
            FROM activity_records
            WHERE project_name = :project
            LIMIT 20000
        """), {"project": project})

        updates = {}
        for row in result:
            record_id, window_title = row

            # Try to extract original project name from window title
            if window_title and ' - ' in window_title:
                # Pattern: "filename - projectname"
                parts = window_title.split(' - ')
                if len(parts) >= 2:
                    original_project = parts[-1].strip()
                    # Clean up
                    original_project = re.sub(r'\s*\(.*?\)\s*$', '', original_project)

                    if original_project and len(original_project) >= 3:
                        if original_project not in updates:
                            updates[original_project] = []
                        updates[original_project].append(record_id)

        # Update records in batches
        for orig_name, record_ids in updates.items():
            if orig_name == project:  # Skip if same
                continue

            # Update in batches of 1000
            for i in range(0, len(record_ids), 1000):
                batch = record_ids[i:i+1000]
                placeholders = ','.join([str(x) for x in batch])

                conn.execute(text(f"""
                    UPDATE activity_records
                    SET project_name = :orig_name
                    WHERE id IN ({placeholders})
                """), {"orig_name": orig_name})

            print(f"  Restored {len(record_ids):,} records to: {orig_name}")

        conn.commit()

    # Show current Mahindra projects
    print("\n" + "="*80)
    print("Current Mahindra projects after undo:")
    print("-" * 80)

    result = conn.execute(text("""
        SELECT
            project_name,
            COUNT(*) as count,
            SUM(duration) / 3600.0 as hours
        FROM activity_records
        WHERE LOWER(project_name) LIKE '%mahindra%'
        GROUP BY project_name
        ORDER BY hours DESC
    """))

    for row in result:
        pname, count, hours = row
        print(f"{pname:50} {count:>7,} records  {hours:>8.2f}h")

print("\n" + "="*80)
print("COMPLETE!")
print("="*80 + "\n")
