import os

exec_file = r"C:\Users\intel\AppData\Local\OptimusRuntime\Labs\AR74\12_ar88_authority_operational_closure\candidate_workspace\app\remediation\self_repair\promotion_executor.py"

with open(exec_file, "r", encoding="utf-8") as f:
    content = f.read()

old_rollback = """    def rollback(self, artifact: RollbackArtifact, target_override_path: Optional[str] = None) -> bool:
        \"\"\"
        AR-88 Authorized Rollback:
        1. Verifies promotion identity and artifact integrity.
        2. Validates canonical path authorization: rejects unauthorized paths or production targets.
        3. Validates original bytes and hash match prior to write.
        4. Atomic replace with verified post-rollback hash check.
        \"\"\"
        artifact.rollback_triggered = True
        if not artifact or not getattr(artifact, "promotion_id", None):
            logger.error("[PromotionExecutor] Rollback rejected: invalid or arbitrary artifact")
            if artifact:
                artifact.error = "ARBITRARY_ARTIFACT_REJECTED"
            return False

        # Verify artifact ownership if tracked
        if artifact.promotion_id in self.rollback_artifacts:
            known_art = self.rollback_artifacts[artifact.promotion_id]
            if known_art.original_hash != artifact.original_hash:
                artifact.error = "ARTIFACT_OWNERSHIP_MISMATCH"
                logger.error("[PromotionExecutor] Rollback rejected: original_hash mismatch with tracked artifact")
                return False

        effective_target = target_override_path or artifact.target_path
        target_canon = os.path.realpath(os.path.abspath(str(effective_target))).replace("\\\\", "/").lower()
        prod_canon = "c:/xampp/htdocs/digital optimus"
        
        # Unauthorized target protection: strictly block rollback targeting production unless authorized
        if target_canon == prod_canon or target_canon.startswith(prod_canon + "/"):
            artifact.error = "UNAUTHORIZED_PRODUCTION_ROLLBACK_BLOCKED"
            artifact.rollback_completed = False
            artifact.production_restored = False
            logger.error("[PromotionExecutor] Rollback blocked: target resolves to protected production path %s", target_canon)
            return False"""

new_rollback = """    def rollback(self, artifact: RollbackArtifact) -> bool:
        \"\"\"
        AR-88 Authorized Rollback:
        1. Verifies promotion identity: promotion_id MUST exist and be registered in self.rollback_artifacts.
        2. Strictly blocks unrecorded, synthetic, or arbitrary rollback artifacts (ROLLBACK_BLOCKED).
        3. Verifies exact canonical target_path, original_hash, and candidate_hash match registered record.
        4. Validates original bytes snapshot and its SHA256 integrity prior to physical write.
        5. Strictly blocks arbitrary targets or target override paths.
        6. Production rollbacks require separate authorized recovery procedure; blocked by default.
        7. Atomic replace with verified post-rollback hash check.
        \"\"\"
        if not artifact:
            logger.error("[PromotionExecutor] Rollback rejected: artifact is None")
            return False
            
        artifact.rollback_triggered = True
        promo_id = getattr(artifact, "promotion_id", None)
        if not promo_id:
            logger.error("[PromotionExecutor] Rollback rejected: missing promotion_id")
            artifact.error = "ROLLBACK_BLOCKED: MISSING_PROMOTION_ID"
            return False

        # REQUIREMENT 2: Must be registered in self.rollback_artifacts
        if promo_id not in self.rollback_artifacts:
            artifact.error = "ROLLBACK_BLOCKED: UNREGISTERED_PROMOTION_ID"
            artifact.rollback_completed = False
            artifact.production_restored = False
            logger.error("[PromotionExecutor] Rollback blocked: promotion_id %s is not registered in executor registry", promo_id)
            return False

        known_art = self.rollback_artifacts[promo_id]

        # Verify exact target_path match
        target_p = Path(artifact.target_path)
        known_target_p = Path(known_art.target_path)
        if target_p.resolve() != known_target_p.resolve():
            artifact.error = "ROLLBACK_BLOCKED: TARGET_PATH_MISMATCH"
            artifact.rollback_completed = False
            logger.error("[PromotionExecutor] Rollback blocked: target_path does not match registered artifact")
            return False

        # Verify original_hash match
        if artifact.original_hash != known_art.original_hash:
            artifact.error = "ROLLBACK_BLOCKED: ORIGINAL_HASH_MISMATCH"
            artifact.rollback_completed = False
            logger.error("[PromotionExecutor] Rollback blocked: original_hash mismatch with registered record")
            return False

        # Verify candidate_hash match if present
        if getattr(artifact, "candidate_hash", None) and getattr(known_art, "candidate_hash", None):
            if artifact.candidate_hash != known_art.candidate_hash:
                artifact.error = "ROLLBACK_BLOCKED: CANDIDATE_HASH_MISMATCH"
                artifact.rollback_completed = False
                logger.error("[PromotionExecutor] Rollback blocked: candidate_hash mismatch with registered record")
                return False

        effective_target = artifact.target_path
        target_canon = os.path.realpath(os.path.abspath(str(effective_target))).replace("\\\\", "/").lower()
        prod_canon = "c:/xampp/htdocs/digital optimus"
        
        # Production target protection: strictly block rollback targeting production without external supervisor authorization
        if target_canon == prod_canon or target_canon.startswith(prod_canon + "/"):
            artifact.error = "UNAUTHORIZED_PRODUCTION_ROLLBACK_BLOCKED"
            artifact.rollback_completed = False
            artifact.production_restored = False
            logger.error("[PromotionExecutor] Rollback blocked: target resolves to protected production path %s", target_canon)
            return False"""

if old_rollback in content:
    content = content.replace(old_rollback, new_rollback)
    with open(exec_file, "w", encoding="utf-8") as f:
        f.write(content)
    print("SUCCESS: promotion_executor.py rollback() updated with strict registry & path enforcement!")
else:
    print("ERROR: old_rollback block not found!")

