import os,shutil,fdb,time, socket
import re,datetime,funkce


def get_medicus_connection():
    """
    Connect to Firebird 'medicus.fdb' depending on computer name.
    Returns fdb.Connection or raises RuntimeError if unknown or connection fails.
    """
    computer_name = socket.gethostname().upper()
    try:
        if computer_name == "Z230":
            print("Computer name is Z230")
            cesta = r"u:\dropboxtest\Ordinace\Dokumentace_ke_zpracování"
            cestazpracovana = r"u:\Dropboxtest\Ordinace\Dokumentace_zpracovaná"
            return fdb.connect(dsn=r"localhost:c:\medicus 3\data\medicus.fdb", user="SYSDBA", password="masterkey", charset="win1250"),cesta,cestazpracovana
        elif computer_name == "LEKAR":
            print("Computer name is LEKAR")
            cesta = r"z:\dropbox\Ordinace\Dokumentace_ke_zpracování"
            cestazpracovana = r"z:\Dropbox\Ordinace\Dokumentace_zpracovaná"
            return fdb.connect(dsn=r"localhost:m:\medicus\data\medicus.fdb", user="SYSDBA", password="masterkey", charset="win1250"),cesta,cestazpracovana
        elif computer_name in ("SESTRA", "POHODA"):
            print("Computer name is SESTRA or POHODA")
            cesta = r"z:\dropbox\Ordinace\Dokumentace_ke_zpracování"
            cestazpracovana = r"z:\Dropbox\Ordinace\Dokumentace_zpracovaná"
            return fdb.connect(dsn=r"192.168.1.10:m:\medicus\data\medicus.fdb", user="SYSDBA", password="masterkey", charset="win1250"),cesta,cestazpracovana
        else:
            raise RuntimeError(f"❌ Unknown computer name: {computer_name}")

    except Exception as e:
        print(f"⚠️ Error connecting to Medicus on {computer_name}: {e}")
        raise

#toto volání současně nadefinuje cesty do dropboxu
conn,cesta,cestazpracovana=get_medicus_connection()


def is_encodable_win1250(text: str) -> bool:
    try:
        text.encode("cp1250")
        return True
    except UnicodeEncodeError:
        return False

def make_win1250_safe(text: str) -> str:
    return text.encode("cp1250", errors="replace").decode("cp1250").replace("?", "_")

def restore_files_for_import(retezec):
    drop=r"u:\Dropbox\!!!Days\Downloads Z230\Dokumentace"
    next=r"u:\NextcloudOrdinace\Dokumentace_ke_zpracování"

    # Check if the directory exists
    if not os.path.exists(drop):
        print(f"The directory '{drop}' does not exist.")
        return

    # Iterate over all files and subdirectories in the directory
    for item in os.listdir(drop):
        item_path = os.path.join(drop, item)

        # If it's a file or a symbolic link, delete it
        if os.path.isfile(item_path) or os.path.islink(item_path):
            os.unlink(item_path)
            print(f"Deleted file: {item_path}")

        # If it's a directory, delete it recursively
        elif os.path.isdir(item_path):
            shutil.rmtree(item_path)
            print(f"Deleted directory: {item_path}")

    for item in os.listdir(next):
        item_path = os.path.join(next, item)
        # If it's a file finished with PDF, copy it
        if os.path.isfile(item_path) and item_path.endswith(".pdf") and retezec in item_path:
            shutil.copy(item_path,os.path.join(drop,item))
            print(f"Copied file: {item_path}")


def kontrola_rc(rc,connection):
    cur = connection.cursor()
    cur.execute("select count(*),idpac from kar where rodcis=? group by idpac",(rc,))
    row = cur.fetchone()
    if row:
        return row[1]
    else:
        return False

def kontrola_struktury(souborname,connection):
    if souborname.endswith('.pdf'):
        #kontrola struktury
        pattern=re.compile(r'(^\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]')
        match=pattern.search(souborname)
        # print(souborname)
        vpohode=True
        if match and len(match.groups())==5:
            datum=match.group(2)
            try:
                datum_object = datetime.datetime.strptime(datum,"%Y-%m-%d").date()
                # print(datum_object)
            except:
                vpohode=False
                return vpohode
            cur = connection.cursor()
            cur.execute("select count(*) from kar where rodcis=?", (match.group(1),))
            row = cur.fetchone()[0]
            if row!=1:
                vpohode = False
                return vpohode
        else:
            vpohode=False
            return vpohode
    else:
        vpohode=False
        return vpohode
    return vpohode

def vrat_info_o_souboru(souborname, connection):
    pattern = re.compile(r'(^\d{9,10}) (\d{4}-\d{2}-\d{2}) (\w+, \w.+?) \[(.+?)\] \[(.*?)\]')
    match = pattern.search(souborname)
    rc = match.group(1)
    datum = datetime.datetime.strptime(match.group(2), "%Y-%m-%d").date()
    jmeno = match.group(3)
    prvnizavorka = match.group(4)
    druhazavorka = match.group(5)
    cur=connection.cursor()
    cur.execute("select idpac from kar where rodcis=?",(rc,))
    idpac = cur.fetchone()[0]
    datumsouboru = datetime.datetime.fromtimestamp(os.path.getctime(os.path.join(cesta,souborname)))
    return (rc,idpac,datum,jmeno,prvnizavorka,druhazavorka,souborname,datumsouboru)

def prejmenuj_chybny_soubor(souborname,cesta):
    if souborname[0]!="♥":
        soubornovy = "♥" + souborname
        os.rename(os.path.join(cesta,souborname),os.path.join(cesta,soubornovy))



# print(kontrola_struktury(ss))
# info=vrat_info_o_souboru(ss)
# print(kontrola_rc(info[0],conn))

# restore_files_for_import("")
# restore_files_for_import("346204097")

info=[]
for soubor in os.listdir(cesta):
    plna_cesta = os.path.join(cesta, soubor)
    if not os.path.isfile(plna_cesta):
        continue  # skip folders or anything that’s not a regular fil

    if not is_encodable_win1250(soubor):
        safe_name = make_win1250_safe(soubor)
        novy_plna_cesta = os.path.join(cesta, safe_name)

        print(f"⚠️  Renaming invalid filename:\n   {soubor} → {safe_name}")
        os.rename(plna_cesta, novy_plna_cesta)

        # Update variable for later processing
        soubor = safe_name
        plna_cesta = novy_plna_cesta

    print(soubor)
    if kontrola_struktury(soubor,conn):
        info.append(vrat_info_o_souboru(soubor,conn))
        # os.remove(os.path.join(cesta,soubor))
    else:
        prejmenuj_chybny_soubor(soubor,cesta)

info = sorted(info, key=lambda x: (x[0], x[1]))
print(info)

skupiny={}
for row in info:
    skupiny[row[0]]=[]
for row in info:
    skupiny[row[0]].append(row)
# print(skupiny)

# rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
# {\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
# {\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
# \uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par
# \pard\s10{\*\bkmkstart 0}\plain\cs22\f0\ul\fs20\cf1 BOOKMARKNAMESTEXT{\*\bkmkend 0}\par
# \pard\s10\plain\cs15\f0\fs20 \par
# }"""

rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
\uc1\pard\s10\plain\cs20\f0\i\fs20 P\'f8\'edlohy:\par
BOOKMARKSTEXT
\pard\s10\plain\cs15\f0\fs20 \par
}"""

for key in skupiny.keys():
    rtf = r"""{\rtf1\ansi\ansicpg1250\uc1\deff0\deflang1029{\info{\bookmarks BOOKMARKNAMES }}{\fonttbl{\f0\fnil\fcharset238 Arial;}{\f5\fnil\fcharset238 Symbol;}}
{\colortbl ;\red0\green0\blue255;\red0\green128\blue0;\red0\green0\blue0;}
{\stylesheet{\s10\fi0\li0\ql\ri0\sb0\sa0 Vlevo;}{\*\cs15\f0\fs20 Norm\'e1ln\'ed;}{\*\cs20\f0\i\fs20 Z\'e1hlav\'ed;}{\*\cs22\f0\ul\fs20\cf1 Odkaz;}}
\uc1\pard\s10\plain\cs20\f0\i\fs20 Vlo\'9eena skenovan\'e1 dokumentace:\par
BOOKMARKSTEXT
\pard\s10\plain\cs15\f0\fs20\par
}"""


    # if key=="8257300425": #346204097
    if True:
        prvnibookmark=True
        print(key,len(skupiny[key]))
        cislo=9
        poradi=0
        bookmark=""
        bookmarks=""
        for row in skupiny[key]:
            # print(row)
            pacid=row[1]
            filename=row[6]
            fileid=funkce.zapis_file(vstupconnection=conn, idpac=row[1],
                              cesta=cesta, souborname=row[6], prvnizavorka=row[4],
                              soubordate=row[2], souborfiledate=row[7], poznamka=row[5])

            for attempt in range(3):
                try:
                    # Replace this with the command that might raise an error
                    if not os.path.exists(os.path.join(cestazpracovana,row[6])):
                        shutil.move(os.path.join(cesta,row[6]), os.path.join(cestazpracovana,row[6]))
                        print("Command succeeded!")
                        break  # Exit the loop if the command succeeds
                    else:
                        now = datetime.datetime.now()
                        datetime_string = now.strftime("%Y-%m-%d %H-%M-%S")
                        print(os.path.join(cestazpracovana,row[6][:-4]+" "+datetime_string+".pdf"))
                        shutil.move(os.path.join(cesta,row[6]),os.path.join(cestazpracovana,row[6][:-4]+" "+datetime_string+".pdf"))
                        print("Command succeeded!")
                        break  # Exit the loop if the command succeeds
                except Exception as e:
                    print(f"Attempt {attempt + 1} failed: {e}")
                    if attempt < 3 - 1:
                        print(f"Retrying in {5} seconds...")
                        time.sleep(5)
                    else:
                        print("Max retries reached. Command failed.")


            filename=funkce.convert_to1250(filename)
            print("Encodedfilename", filename)
            filenameforbookmark=row[2].strftime('%Y-%m-%d')+" "+row[4]+": "+row[5]
            bookmark=bookmark+'"'+filenameforbookmark+'","Files:'+str(fileid)+'",'+str(cislo)+";"
            cislo+=7
            # print(bookmark)
            if prvnibookmark:
                bookmarks=bookmarks+r'\pard\s10{\*\bkmkstart '+str(poradi)+r"}\plain\cs22\f0\ul\fs20\cf1 "+filenameforbookmark+r"{\*\bkmkend "+str(poradi)+r"}\par"
                prvnibookmark=False
            else:
                bookmarks=bookmarks+r'\pard\s10{\*\bkmkstart '+str(poradi)+r"}" + filenameforbookmark + r"{\*\bkmkend " + str(poradi) + r"}\par"
        bookmark=bookmark[:-1]
        # bookmarks=bookmarks[:-2]
        print(bookmark)
        print(bookmarks)

        rtf = rtf.replace("BOOKMARKNAMES", bookmark)
        rtf=rtf.replace("BOOKMARKSTEXT",bookmarks)
        print(rtf)
        dekursid = funkce.get_dekurs_id(conn)
        datumzapisu = datetime.datetime.now().date()
        caszapisu = datetime.datetime.now().time()
        cur=conn.cursor()
        cur.execute("insert into dekurs (id,iduzi,idprac,idodd,idpac,datum,cas,dekurs)"
                    " values(?,?,?,?,?,?,?,?)",
                    (dekursid,6,2,2, row[1],datumzapisu,caszapisu, rtf))
        conn.commit()
         # rtf = rtf.replace("FILEID", str(idfile))
         #Zde zapisujeme soubor
         # fileid=funkce.zapis_file(conn,row[1],cesta,row[6],row[4],row[2],row[7],row[5])
         # zapis_dekurs(vstupconnection, idpac, idodd, iduzi, idprac, idfile, filename, text, datumzpravy,datumsouboru)
         # return (rc, idpac, datum, jmeno, prvnizavorka, druhazavorka, souborname, datumsouboru)

         # Zde zapisujeme dekurs
         # text=row[2].strftime("%Y-%m-%d")+" "+row[4].strip()+": "+row[5].strip()
         # funkce.zapis_dekurs(conn, row[1], 2, 6, 2, fileid, text, text, row[7], row[2])
         # os.remove(os.path.join(cesta, soubor))

