"""Script to clean up junk/synthetic test documents from erp_documents table."""

import sys
import io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")

from app.core.postgres.erp_client import ErpDatabaseClient


def cleanup():
    client = ErpDatabaseClient()
    with client.get_connection() as conn:
        with conn.cursor() as cur:
            # 1. Inspect targets before deletion
            cur.execute("""
                SELECT id, document_code, document_title, is_active_version
                FROM erp_documents
                WHERE document_title LIKE '%kỹ sư Quỳnh%'
                   OR (document_code = '01/2026/TTR-DSC' AND is_active_version = FALSE);
            """)
            targets = cur.fetchall()
            print(f"Found {len(targets)} junk records to clean up:")
            for t in targets:
                print(f"  - [{t['document_code']}] {t['document_title']} (ID: {t['id']})")

            if not targets:
                print("No junk records found.")
                return

            target_ids = [t["id"] for t in targets]

            # 2. Execute deletion
            cur.execute(
                "DELETE FROM erp_documents WHERE id = ANY(%s);",
                (target_ids,)
            )
            deleted_count = cur.rowcount
            conn.commit()
            print(f"\nSuccessfully deleted {deleted_count} junk records.")

            # 3. Check remaining records
            cur.execute("""
                SELECT id, document_code, document_title, is_active_version, file_path
                FROM erp_documents
                ORDER BY created_at ASC;
            """)
            remaining = cur.fetchall()
            print(f"\nRemaining legitimate documents ({len(remaining)}):")
            for r in remaining:
                print(f"  - [{r['document_code']}] {r['document_title']} (Path: {r['file_path']})")


if __name__ == "__main__":
    cleanup()
