import os, sys
from typing import Optional

_original_log_artifact = None
_enabled = False

def enable(api_key=None, sync=False):
    global _original_log_artifact, _enabled
    if _enabled: return
    import wandb
    from umarise_wandb.anchor import anchor_file
    _original_log_artifact = wandb.Run.log_artifact
    def _patched(self, artifact, *args, **kwargs):
        result = _original_log_artifact(self, artifact, *args, **kwargs)
        try:
            if hasattr(artifact, "manifest") and artifact.manifest:
                for entry in artifact.manifest.entries.values():
                    lp = getattr(entry, "local_path", None)
                    if lp and os.path.exists(lp):
                        anchor_file(lp, run=self, api_key=api_key, sync=sync)
        except Exception as e:
            print(f"[umarise] ⚠ auto_anchor: {e}", file=sys.stderr)
        return result
    wandb.Run.log_artifact = _patched
    _enabled = True

def disable():
    global _original_log_artifact, _enabled
    if _original_log_artifact:
        import wandb
        wandb.Run.log_artifact = _original_log_artifact
        _original_log_artifact = None
    _enabled = False
