import json
import os
from datetime import datetime

# =========================================================
# FIND INPUT JSON IN CURRENT DIRECTORY
# =========================================================

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

json_files = [
    f for f in os.listdir(SCRIPT_DIR)
    if f.lower().endswith(".json")
]

if len(json_files) == 0:
    raise RuntimeError("No JSON file found in script directory.")

if len(json_files) > 1:
    raise RuntimeError(
        "Multiple JSON files found. Keep only ONE JSON file in the folder:\n"
        + "\n".join(json_files)
    )

INPUT_JSON = os.path.join(SCRIPT_DIR, json_files[0])

timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
OUTPUT_JSON = os.path.join(
    SCRIPT_DIR,
    "tag_export_modified_%s.json" % timestamp
)

# =========================================================
# USER SELECTION
# =========================================================

print("")
print("Select target tag source:")
print("  1 = OPC")
print("  2 = MEMORY")
print("")

choice = input("Enter choice (1 or 2): ").strip()

if choice == "1":
    TARGET_MODE = "OPC"
elif choice == "2":
    TARGET_MODE = "MEMORY"
else:
    raise ValueError("Invalid selection. Must be 1 or 2.")

print("Target mode:", TARGET_MODE)

# =========================================================
# MODIFICATION LOGIC (SYSTEM FOLDER ONLY)
# =========================================================

modified_count = 0

def process_node(node):
    global modified_count

    if not isinstance(node, dict):
        return

    tag_type = node.get("tagType")
    value_source = node.get("valueSource")

    # Modify ONLY atomic tags
    if tag_type == "AtomicTag":
        if TARGET_MODE == "MEMORY":
            if value_source != "memory":
                node["valueSource"] = "memory"
                node["opcItemPath"] = ""
                modified_count += 1

        elif TARGET_MODE == "OPC":
            if value_source != "opc":
                node["valueSource"] = "opc"
                modified_count += 1

    # Recurse deeper
    for key in ("tags", "children"):
        children = node.get(key)
        if isinstance(children, list):
            for child in children:
                process_node(child)


def find_and_process_system(root):
    """
    Locate the 'System' folder and ONLY process its contents.
    """
    if not isinstance(root, dict):
        return

    if root.get("tagType") == "Folder" and root.get("name") == "System":
        process_node(root)
        return

    for key in ("tags", "children"):
        children = root.get(key)
        if isinstance(children, list):
            for child in children:
                find_and_process_system(child)

# =========================================================
# LOAD → FIND SYSTEM → PROCESS → WRITE
# =========================================================

with open(INPUT_JSON, "r") as f:
    data = json.load(f)

if isinstance(data, list):
    for root in data:
        find_and_process_system(root)
else:
    find_and_process_system(data)

with open(OUTPUT_JSON, "w") as f:
    json.dump(data, f, indent=2)

# =========================================================
# SUMMARY
# =========================================================

print("")
print("======================================")
print(" Tag Source Update Complete")
print("======================================")
print(" Target Folder :", "System")
print(" Target Mode   :", TARGET_MODE)
print(" Tags Modified :", modified_count)
print(" Input File    :", INPUT_JSON)
print(" Output File   :", OUTPUT_JSON)
print("======================================")

if modified_count == 0:
    print("⚠ WARNING: No tags were modified inside 'System'.")
