from pathlib import Path
import getpass
import re

username = getpass.getuser()
address = Path(f"C:/Users/{username}/AppData/Roaming/..Tdatabase/data")
address.mkdir(parents=True, exist_ok=True)

lg = 'en'

def set_lang(lang=None):
    global lg
    if lang == 'fa':
        lg = 'fa'
        print('Zaban Farsi Shod.')
    elif lang == 'en':
        lg = 'en'
        print('Language Is English.')
    else:
        if lg == 'en':
            print('Language Is Not Defined \n Languages :\n fa/en')
        if lg == 'fa':
            print('Zaban Mord Nazar Yaft Nashod \n Zaban ha : \n fa/en')

class _TDB:
    def __init__(self, file_path, db_name):
        self.path = file_path
        self.name = db_name
        self.lang = lg

    def _parse(self):
        if not self.path.exists():
            return {}
        with open(self.path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        match = re.search(r'DATABASE\s+(\w+)\s*\{([\s\S]*)\}', content)
        if not match:
            return {}
        
        body = match.group(2)
        data = {}
        for line in body.split('\n'):
            line = line.strip()
            if not line or line in ['{', '}']:
                continue
            if line.startswith(','):
                line = line[1:]
            
            if ':' in line:
                key, values_str = line.split(':', 1)
                key = key.strip()
                values = [v.strip() for v in values_str.split(',') if v.strip()]
                data[key] = values
        return data

    def _write(self, data):
        lines = [f"DATABASE {self.name} {{"]
        for key, values in data.items():
            val_str = ", ".join(values) + ","
            lines.append(f"    {key} : {val_str}")
        lines.append("}")
        
        with open(self.path, 'w', encoding='utf-8') as f:
            f.write("\n".join(lines))

    def add_val(self, key=None, val=None):
        if not key or not val:
            msg = "Error: Key and Value are required!" if self.lang == 'en' else "Khata: Key va Value lazem ast!"
            print(msg)
            return

        data = self._parse()
        if key not in data:
            data[key] = []
        data[key].append(val)
        self._write(data)
        
        msg = f"Value '{val}' added to '{key}'." if self.lang == 'en' else f"Value '{val}' be '{key}' ezafe shod."
        print(msg)

    def read_cat(self):
        data = self._parse()
        return list(data.keys())

    def read_content(self, key=None):
        if not key:
            return None
        data = self._parse()
        return data.get(key)

    def read_user(self, search_key, search_value):
        data = self._parse()
        if search_key not in data:
            return None
            
        try:
            index = data[search_key].index(search_value)
        except ValueError:
            return None

        user_info = {}
        for key, values in data.items():
            if index < len(values):
                user_info[key] = values[index]
        return user_info

    def del_val(self, key, val):
        data = self._parse()
        if key not in data or val not in data[key]:
            print("Item not found.")
            return

        index = data[key].index(val)
        for k in data:
            if index < len(data[k]):
                data[k].pop(index)
        
        self._write(data)
        print(f"Item '{val}' deleted.")

    def update_val(self, key, old_val, new_val):
        data = self._parse()
        if key not in data or old_val not in data[key]:
            print("Old value not found.")
            return

        index = data[key].index(old_val)
        data[key][index] = new_val
        
        self._write(data)
        print(f"Updated '{old_val}' to '{new_val}'.")

def db_open(filename):
    file_path = address / filename
    db_name = filename.replace(".tdb", "")
    
    if file_path.exists():
        if lg == 'en': 
            print("Hello , Tdatabase Ready")
        else:
            print('Salam, Tdatabase Amade Ast')
        return _TDB(file_path, db_name)
    else:
        if lg == 'en':
            print("ERROR 404 : Database Not Found")
        else:
            print('Khata 404 : Database Morede Nazar Peida Nashod')
        return None

def total_db():
    return [file.stem for file in address.glob("*.tdb")]
