import os
import shutil
import sys

sys.path.insert(0, os.path.abspath("."))
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")


def reorganize_and_clean():
    base_tools = "tools"

    seeds_dir = os.path.join(base_tools, "seeds")
    maint_dir = os.path.join(base_tools, "maintenance")
    verif_dir = os.path.join(base_tools, "verification")

    os.makedirs(seeds_dir, exist_ok=True)
    os.makedirs(maint_dir, exist_ok=True)
    os.makedirs(verif_dir, exist_ok=True)

    # 1. Map core files to appropriate directories
    seeds_files = [
        "seed_all_comprehensive_real_projects.py",
        "seed_comprehensive_erp_real_data.py",
        "seed_real_employee_work_logs.py",
        "seed_real_employee_work_logs_support.py",
        "enrich_all_database_invoices.py",
        "enrich_howo_fleet.py",
    ]

    maint_files = [
        "ingest_legal_knowledge.py",
        "ingest_people_knowledge.py",
        "ingest_unified_knowledge.py",
        "crawl_construction_laws.py",
        "ocr_hsnl_pages.py",
        "kenh_xay_gold_reference_ingest.py",
        "kenh_xay_gold_reference_ingest_support.py",
        "hd2026_ingest.py",
        "ingest_dot1_pilot.py",
    ]

    verif_files = [
        "test_real_projects_ui.py",
        "test_mtt_invoice_ui_browser.py",
        "test_equipment_tabs_browser.py",
        "test_invoices_category_ui_browser.py",
        "test_machinery_invoice_ui_browser.py",
        "test_truth_extraction_browser.py",
        "test_truthful_invoice_sync_browser.py",
        "test_project_wbs_browser.py",
        "test_advanced_features_browser.py",
        "test_ai_budget_browser.py",
        "test_browser_navigation.py",
        "test_master_erp_suite.py",
        "test_enterprise_hrm_and_fleet_browser.py",
        "test_navigation_menus_browser.py",
        "test_resizable_equipment_ui.py",
        "test_redesigned_modal_and_resizing.py",
        "test_sidebar_user_layout_browser.py",
    ]

    for f in seeds_files:
        src = os.path.join(base_tools, f)
        if os.path.exists(src):
            shutil.copy2(src, os.path.join(seeds_dir, f))
            os.remove(src)
            print(f"Moved -> seeds/{f}")

    for f in maint_files:
        src = os.path.join(base_tools, f)
        if os.path.exists(src):
            shutil.copy2(src, os.path.join(maint_dir, f))
            os.remove(src)
            print(f"Moved -> maintenance/{f}")

    for f in verif_files:
        src = os.path.join(base_tools, f)
        if os.path.exists(src):
            shutil.copy2(src, os.path.join(verif_dir, f))
            os.remove(src)
            print(f"Moved -> verification/{f}")

    # Keep a reference copy of test_real_projects_ui.py in tools for legacy quick runs
    shutil.copy2(
        os.path.join(verif_dir, "test_real_projects_ui.py"),
        os.path.join(base_tools, "test_real_projects_ui.py"),
    )

    # 2. Clean scratch / probe files in base_tools
    keep_in_root_tools = ["reorganize_tools_and_cleanup.py", "test_real_projects_ui.py"]

    deleted_count = 0
    for f in os.listdir(base_tools):
        fp = os.path.join(base_tools, f)
        if os.path.isfile(fp) and f not in keep_in_root_tools:
            try:
                os.remove(fp)
                deleted_count += 1
            except Exception as ex:
                print(f"Could not delete {f}: {ex}")

    print(
        f"\n[CLEANUP] Deleted {deleted_count} obsolete probe/scratch files from tools/!"
    )
    print("Organized into tools/seeds, tools/maintenance, tools/verification.")


if __name__ == "__main__":
    reorganize_and_clean()
