import datetime

paws_dict = {}

# ─────────────────────────────────────────────
# Load from file
# ─────────────────────────────────────────────

def load_from_txt():
    try:
        with open("safe_paws.txt", "r", encoding="utf-8") as f:
            for line in f:
                row = line.strip().split(";")
                paws_dict[int(row[0])] = [row[1], row[2], row[3], row[4], int(row[5]), row[6]]
    except FileNotFoundError:
        pass

# ─────────────────────────────────────────────
# Get next incremental ID
# ─────────────────────────────────────────────

def get_next_id():
    if not paws_dict:
        return 1
    all_ids = []
    for k in paws_dict.keys():
        all_ids.append(int(k))
    return max(all_ids) + 1

# ─────────────────────────────────────────────
# Add paw
# ─────────────────────────────────────────────

def add_paw():
    name = ""
    while not name:
        name = input("Paw name: ")

    specie = ""
    while not specie:
        specie = input("Paw specie: ")

    size = ""
    while not size or size.lower() not in ["small", "medium", "big"]:
        size = input("Paw size (small/medium/big only): ")
    size = size.lower()

    health = ""
    while not health or health.lower() not in ["healthy", "ill"]:
        health = input("Paw health status (healthy/ill only): ")
    health = health.lower()

    while True:
        try:
            age = int(input("Paw age: "))
            if age > 0:
                break
            print("Paw age must be greater than 0.")
        except ValueError:
            print("Invalid paw age. Enter a number.")

    id = get_next_id()

    with open("safe_paws.txt", "a", encoding="utf-8") as f:
        f.write(f"{id};{name};{specie};{size};{health};{age};available\n")

    load_from_txt()

# ─────────────────────────────────────────────
# Advanced search
# ─────────────────────────────────────────────

def adv_search():
    specie = input("Searched specie (0 for all): ").strip()

    size = ""
    while not size or size.lower() not in ["small", "medium", "big", "0"]:
        size = input("Searched size (small/medium/big, 0 for all): ")
    size = size.lower()

    while True:
        try:
            age = int(input("Searched max age (0 for all): "))
            if age >= 0:
                break
            print("Age must be 0 or greater.")
        except ValueError:
            print("Invalid age. Enter a number.")

    results = {}
    for key in paws_dict:
        if paws_dict[key][5] == "available":
            if specie == "0" or paws_dict[key][1] == specie:
                if size == "0" or paws_dict[key][2] == size:
                    if age == 0 or paws_dict[key][4] <= age:
                        results[key] = paws_dict[key]

    return results

# ─────────────────────────────────────────────
# Print search results
# ─────────────────────────────────────────────

def print_adv_search():
    results = adv_search()
    for key in results:
        print(f"ID: {key} - {results[key][0]} is a {results[key][4]} years old, {results[key][2]} sized {results[key][1]}. Health status: {results[key][3]}.")

# ─────────────────────────────────────────────
# Edit health status
# ─────────────────────────────────────────────

def edit_health():
    available_paws = {}
    adopted_paws = {}
    editable = False

    for key in paws_dict:
        if paws_dict[key][5] == "available":
            available_paws[key] = paws_dict[key]
        else:
            adopted_paws[key] = paws_dict[key]

    while True:
        try:
            id = int(input("Paw id: "))
            if id in available_paws.keys():
                print("Paw identified!")
                editable = True
                break
            elif id in adopted_paws.keys():
                print("Paw is adopted! You can't edit an adopted paw!")
                break
        except ValueError:
            print("Invalid ID. Enter a number.")

    if editable:
        health = ""
        while not health or health.lower() not in ["healthy", "ill"]:
            health = input("Paw health status update (healthy/ill only): ")
        paws_dict[id][3] = health.lower()
        print(f"{paws_dict[id][0].upper()} was successfully updated. New health status is: {paws_dict[id][3].upper()}.")

        with open("safe_paws.txt", "w", encoding="utf-8") as f:
            for key in paws_dict:
                f.write(f"{key};{paws_dict[key][0]};{paws_dict[key][1]};{paws_dict[key][2]};{paws_dict[key][3]};{paws_dict[key][4]};{paws_dict[key][5]}\n")
        print("safe_paws.txt was updated!")
        load_from_txt()

# ─────────────────────────────────────────────
# Register adoption
# ─────────────────────────────────────────────

def paw_adopted():
    available_paws = {}
    adopted_paws = {}

    for key in paws_dict:
        if paws_dict[key][5] == "available":
            available_paws[key] = paws_dict[key]
        else:
            adopted_paws[key] = paws_dict[key]

    while True:
        try:
            id = int(input("Adopted paw id: "))
            if id in available_paws.keys():

                owner_name = ""
                while not owner_name:
                    owner_name = input("New owner name: ")

                owner_contact = ""
                while not owner_contact:
                    owner_contact = input("New owner contact: ")

                adoption_date = datetime.date.today().strftime("%Y-%m-%d")

                with open("adopted_paws.txt", "a", encoding="utf-8") as f:
                    f.write(f"{id};{owner_name};{owner_contact};{adoption_date}\n")

                paws_dict[id][5] = "adopted"
                print(f"Great! {paws_dict[id][0].upper()} has a new home.")

                with open("safe_paws.txt", "w", encoding="utf-8") as f:
                    for key in paws_dict:
                        f.write(f"{key};{paws_dict[key][0]};{paws_dict[key][1]};{paws_dict[key][2]};{paws_dict[key][3]};{paws_dict[key][4]};{paws_dict[key][5]}\n")
                print("safe_paws.txt was updated!")
                load_from_txt()
                break

            elif id in adopted_paws.keys():
                print(f"{paws_dict[id][0].upper()} was already adopted.")
                break

        except ValueError:
            print("Invalid ID. Enter a number.")

# ─────────────────────────────────────────────
# Load on start
# ─────────────────────────────────────────────

load_from_txt()

# ─────────────────────────────────────────────
# Menu
# ─────────────────────────────────────────────

while True:
    print("\nSafe Paws Menu")
    option = input("1-Add paw\n2-Adv search\n3-Edit paw health\n4-Register adoption\nq-Quit\nChoose your option: ")
    if option == "1":
        add_paw()
        print("Paw added successfully!")
    elif option == "2":
        if len(adv_search()) > 0:
            print_adv_search()
        else:
            print("No data match your search.")
    elif option == "3":
        edit_health()
    elif option == "4":
        paw_adopted()
    elif option == "q":
        break
    else:
        print("Invalid option!")
