"""Guard checks for Files module responsiveness and spreadsheet safety.
Run from project root: python tools/files_module_guard_check.py --write-report
"""
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
FILES_PAGE = ROOT / "pages" / "files_page.py"
REPORT = ROOT / "data" / "files_module_guard_latest.json"


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--write-report", action="store_true")
    args = parser.parse_args()
    text = FILES_PAGE.read_text(encoding="utf-8", errors="ignore")
    checks = {
        "horizontal_toolbar_canvas": "self.tool_canvas" in text and "self.tool_xbar" in text and "_update_tool_scroll" in text,
        "chunked_file_list_rendering": "_render_file_list_chunk" in text and "_file_list_render_job" in text,
        "file_list_render_cancel": "after_cancel(self._file_list_render_job)" in text,
        "sheet_edit_autosave": "sheet edits should autosave" in text and "self._schedule_autosave()" in text,
        "safe_formula_functions": "_safe_formula_number" in text and "ROUND" in text and "ABS" in text and "SQRT" in text and "POWER" in text,
        "favorite_files": "toggle_current_favorite" in text and "shared_filter_favorites" in text,
        "recent_files": "shared_filter_recent" in text and "last_opened" in text and "_schedule_open_metadata_save" in text,
        "document_copy_content": "copy_doc_content" in text and "shared_copy_content" in text,
        "file_archive_filter": "shared_filter_archive" in text and "toggle_file_archive_by_id" in text,
        "file_properties_dialog": "show_file_properties" in text and "shared_file_properties" in text,
        "office_export_formats": "openpyxl" in text and "from docx import Document" in text,
        "sheet_stats_footer": "_sheet_stats_text" in text and "shared_sheet_stats" in text,
        "lightweight_active_card_refresh": "_refresh_file_card_states" in text and "self._file_cards" in text,
        "folder_organization": "current_folder" in text and "shared_all_folders" in text and "move_file_to_folder_by_id" in text,
    }
    errors = [name for name, ok in checks.items() if not ok]
    payload = {
        "ok": not errors,
        "checks": checks,
        "errors": errors,
    }
    if args.write_report:
        REPORT.parent.mkdir(parents=True, exist_ok=True)
        REPORT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    if errors:
        print("Files module guard failed:")
        for item in errors:
            print(" -", item)
        return 1
    print("Files module guard OK")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
