"""
One-shot script: strips cropKeyframes and autoCropKeyframes from every clip
adjustment in every sequence across every project, while preserving everything else
(cropRect, cropPreset, displayMode, autoFrameSamples, etc.).
"""
import sys, os, json

sys.path.insert(0, os.path.dirname(__file__))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
import django
django.setup()

from apps.editor.models import Project


def strip_keyframes(adj):
    """Recursively remove cropKeyframes / autoCropKeyframes from an adjustment dict."""
    if not isinstance(adj, dict):
        return adj, 0, 0

    manual_removed = 0
    auto_removed = 0
    result = dict(adj)

    if "cropKeyframes" in result:
        manual_removed += len(result["cropKeyframes"]) if isinstance(result["cropKeyframes"], list) else 1
        del result["cropKeyframes"]

    if "autoCropKeyframes" in result:
        auto_removed += len(result["autoCropKeyframes"]) if isinstance(result["autoCropKeyframes"], list) else 1
        del result["autoCropKeyframes"]

    if "byAspect" in result and isinstance(result["byAspect"], dict):
        new_by_aspect = {}
        for aspect_key, aspect_val in result["byAspect"].items():
            if isinstance(aspect_val, dict):
                new_aspect = {}
                for mode_key, mode_val in aspect_val.items():
                    cleaned, m, a = strip_keyframes(mode_val)
                    new_aspect[mode_key] = cleaned
                    manual_removed += m
                    auto_removed += a
                new_by_aspect[aspect_key] = new_aspect
            else:
                new_by_aspect[aspect_key] = aspect_val
        result["byAspect"] = new_by_aspect

    return result, manual_removed, auto_removed


total_manual = 0
total_auto = 0
projects_changed = 0

for p in Project.objects.all():
    draft = p.editor_draft
    if not draft:
        continue

    draft_changed = False
    for seq in draft.get("sequences", []):
        adjs = seq.get("clipDisplayAdjustments")
        if not isinstance(adjs, dict):
            continue
        for block_id in list(adjs.keys()):
            cleaned, m, a = strip_keyframes(adjs[block_id])
            if m or a:
                adjs[block_id] = cleaned
                draft_changed = True
                total_manual += m
                total_auto += a
                print(f"  P{p.id} seq={seq.get('id','')[-28:]} block=...{block_id[-12:]}: -manual={m} -auto={a}")

    if draft_changed:
        p.editor_draft = draft
        p.save(update_fields=["editor_draft"])
        projects_changed += 1
        print(f"  -> Saved P{p.id}")

print()
print(f"Done. Removed manual_kf={total_manual}  auto_kf={total_auto}  projects_saved={projects_changed}")
