# %%
import livsdk.livconfig
from livsdk.smartfs import load_rclone_profile
import lakefs_sdk
import lakefs
from datetime import datetime

from lakefs.client import Client

# %%
repo_name = "test-repo"
rclone_conf = livsdk.livconfig.LivRcloneConfig(rclone_profile_lakefs="lakefsDev")

cred = load_rclone_profile(
    rclone_conf.rclone_profile_lakefs,
    rclone_conf.rclone_config_path
)

configuration = lakefs_sdk.Configuration(
    host = cred["endpoint"],
    username = cred["access_key_id"],
    password = cred["secret_access_key"],
)

clt = Client(username = cred["access_key_id"],
             password = cred["secret_access_key"],
             host = cred["endpoint"])


# %%
def get_branch_head_commit(branch_name):
    commit = lakefs.repository(repo_name,client=clt).branch(branch_name).get_commit()

    print(f"Current HEAD of '{branch_name}': {commit.id}")
    return commit
# %%
initcommit = get_branch_head_commit("init").id

# %%
# Create test branch
hardreset_branch = f"hardreset-{datetime.now().strftime('%Y%m%d%H%M%S')}"
branch=lakefs.repository(repo_name,client=clt).branch(hardreset_branch)
branch.create("init")
print(f"Creatd branch {hardreset_branch}")
# %%
get_branch_head_commit(hardreset_branch)

# %%
# Write a file
try:
    with branch.transact(commit_message="Add datasets") as tx:
        # All operations happen on ephemeral branch
        tx.object("data/file1.csv").upload(data=b"id,value\n1,100\n2,200")
        print("Upload successful - changes will be committed atomically")

    # At this point, transaction is complete and merged
    print("Transaction committed to main")

except Exception as e:
    # If we get here, changes were rolled back
    print(f"Transaction failed and rolled back: {e}")


prior = get_branch_head_commit(hardreset_branch).id

# %%


# %%
print(f"Hardreseting to {initcommit} for branch {hardreset_branch}")
with lakefs_sdk.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = lakefs_sdk.ExperimentalApi(api_client)
    repository = repo_name # str |
    branch = hardreset_branch # str |
    ref = initcommit
    force = True # bool |  (optional) (default to False)

    try:
        # hard reset branch
        api_instance.hard_reset_branch(repository, branch, ref, force=force)
    except Exception as e:
        print("Exception when calling ExperimentalApi->hard_reset_branch: %s\n" % e)

# %%
postreset = get_branch_head_commit(hardreset_branch).id
print("Prior commit ID:", prior)
print("Post-reset commit ID:", postreset)
print("Expected commit ID:", initcommit)
if prior != postreset:
    print("Hard reset successful.")
else:
    print("Hard reset failed.")

# %%


# %%


# %%



