#
#   "contingent-movement" project;
#   author:     gazakbayev.net
#   ver:        1.0
#

import psycopg2
from debug_data.database_creds import CREDS

class Database:
    @staticmethod
    def __connection__():
        return psycopg2.connect(**CREDS)
    @staticmethod
    def initialize():
        conn = Database.__connection__()
        try:
            with conn.cursor() as cur, open("../docs/schema.sql", "r", encoding="utf-8") as f:
                cur.execute(f.read())
            conn.commit()
            print("[Contingent-movement] Initialized database with relations.")
        except Exception as e:
            print(f"[Contingent-movement] [Contingent Movement] Error: {e}")
            conn.rollback()
        finally:
            conn.close()

def physicals_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Physicals (passport_no, name, surname, birthday, phone, mail, citizenship, address, access_card, access_level)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Physicals: {e}")
    finally:
        conn.close()

def supervisors_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Supervisors (person, experience, defended_ratio, qualification)
                VALUES (%s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Supervisors: {e}")
    finally:
        conn.close()

def faculties_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Faculties (name, acronym, head, vice, address)
                VALUES (%s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Faculties: {e}")
    finally:
        conn.close()

def departments_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Departments (name, acronym, founded, head, vice, secretary, faculty_id)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Departments: {e}")
    finally:
        conn.close()

def programs_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Programs (specification, degree, name, parent_id)
                VALUES (%s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Programs: {e}")
    finally:
        conn.close()

def groups_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Groups (group_id, faculty_id, program_id, department_id, study_starts, study_ends)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Groups: {e}")
    finally:
        conn.close()

def students_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            # 1. Сначала проверяем существование всех внешних ключей
            cur.execute("""
                SELECT 1 FROM physicals WHERE passport_no = %s
                UNION ALL
                SELECT 1 FROM groups WHERE group_id = %s
                UNION ALL
                SELECT 1 FROM physicals WHERE passport_no = %s OR %s IS NULL
            """, [data[0], data[1], data[2], data[2]])
            
            if len(cur.fetchall()) < 2 + (1 if data[2] is not None else 0):
                raise ValueError("Invalid foreign key references")

            cur.execute("""
                INSERT INTO Students (person, group_id, supervisor, education_form, status)
                VALUES (%s, %s, %s, %s, %s)
                RETURNING id
            """, data)
            
            inserted_id = cur.fetchone()[0]
            conn.commit()
            return inserted_id
            
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Students: {e}")
        return None
    finally:
        conn.close()

def family_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Family (person, name, surname, kinship, phone, address)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Family: {e}")
    finally:
        conn.close()

def files_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Files (student_id, name, description, extension, size, path)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Files: {e}")
    finally:
        conn.close()

def disciplines_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Disciplines (name, department_id, credit_units, academic_hours, general_hours, is_annual)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Disciplines: {e}")
    finally:
        conn.close()

def statements_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Statements (student_id, discipline_id, examiner, try_no, grade, conducted_at)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Statements: {e}")
    finally:
        conn.close()

def movement_write(data: list):
    conn = Database.__connection__()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                INSERT INTO Movement (student_id, type, new_group, new_status, issued_at)
                VALUES (%s, %s, %s, %s, %s)
            """, data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(f"[Contingent Movement] Error inserting into Movement: {e}")
    finally:
        conn.close()

        
#   /$$$$$$                        /$$     /$$                                           /$$                                                                   
#  /$$__  $$                      | $$    |__/                                          | $$                                                                   
# | $$  \__/  /$$$$$$  /$$$$$$$  /$$$$$$   /$$ /$$$$$$$   /$$$$$$   /$$$$$$  /$$$$$$$  /$$$$$$                                                                 
# | $$       /$$__  $$| $$__  $$|_  $$_/  | $$| $$__  $$ /$$__  $$ /$$__  $$| $$__  $$|_  $$_/                                                                 
# | $$      | $$  \ $$| $$  \ $$  | $$    | $$| $$  \ $$| $$  \ $$| $$$$$$$$| $$  \ $$  | $$                                                                   
# | $$    $$| $$  | $$| $$  | $$  | $$ /$$| $$| $$  | $$| $$  | $$| $$_____/| $$  | $$  | $$ /$$                                                               
# |  $$$$$$/|  $$$$$$/| $$  | $$  |  $$$$/| $$| $$  | $$|  $$$$$$$|  $$$$$$$| $$  | $$  |  $$$$/                                                               
#  \______/  \______/ |__/  |__/   \___/  |__/|__/  |__/ \____  $$ \_______/|__/  |__/   \___/                                                                 
#                                                        /$$  \ $$                                                                                             
#                                                       |  $$$$$$/                                                                                             
#                                                        \______/                                                                                              
#  /$$      /$$                                                                   /$$                                                                          
# | $$$    /$$$                                                                  | $$                                                                          
# | $$$$  /$$$$  /$$$$$$  /$$    /$$ /$$$$$$  /$$$$$$/$$$$   /$$$$$$  /$$$$$$$  /$$$$$$                                                                        
# | $$ $$/$$ $$ /$$__  $$|  $$  /$$//$$__  $$| $$_  $$_  $$ /$$__  $$| $$__  $$|_  $$_/                                                                        
# | $$  $$$| $$| $$  \ $$ \  $$/$$/| $$$$$$$$| $$ \ $$ \ $$| $$$$$$$$| $$  \ $$  | $$                                                                          
# | $$\  $ | $$| $$  | $$  \  $$$/ | $$_____/| $$ | $$ | $$| $$_____/| $$  | $$  | $$ /$$                                                                      
# | $$ \/  | $$|  $$$$$$/   \  $/  |  $$$$$$$| $$ | $$ | $$|  $$$$$$$| $$  | $$  |  $$$$/                                                                      
# |__/     |__/ \______/     \_/    \_______/|__/ |__/ |__/ \_______/|__/  |__/   \___/                                                                        
                                                                                                                                                                                                                                                                                                                                                                                                                                                               
#  /$$                                                               /$$       /$$                                                                      /$$    
# | $$                                                              | $$      | $$                                                                     | $$    
# | $$$$$$$  /$$   /$$        /$$$$$$   /$$$$$$  /$$$$$$$$  /$$$$$$ | $$   /$$| $$$$$$$   /$$$$$$  /$$   /$$  /$$$$$$  /$$    /$$ /$$$$$$$   /$$$$$$  /$$$$$$  
# | $$__  $$| $$  | $$       /$$__  $$ |____  $$|____ /$$/ |____  $$| $$  /$$/| $$__  $$ |____  $$| $$  | $$ /$$__  $$|  $$  /$$/| $$__  $$ /$$__  $$|_  $$_/  
# | $$  \ $$| $$  | $$      | $$  \ $$  /$$$$$$$   /$$$$/   /$$$$$$$| $$$$$$/ | $$  \ $$  /$$$$$$$| $$  | $$| $$$$$$$$ \  $$/$$/ | $$  \ $$| $$$$$$$$  | $$    
# | $$  | $$| $$  | $$      | $$  | $$ /$$__  $$  /$$__/   /$$__  $$| $$_  $$ | $$  | $$ /$$__  $$| $$  | $$| $$_____/  \  $$$/  | $$  | $$| $$_____/  | $$ /$$
# | $$$$$$$/|  $$$$$$$      |  $$$$$$$|  $$$$$$$ /$$$$$$$$|  $$$$$$$| $$ \  $$| $$$$$$$/|  $$$$$$$|  $$$$$$$|  $$$$$$$   \  $//$$| $$  | $$|  $$$$$$$  |  $$$$/
# |_______/  \____  $$       \____  $$ \_______/|________/ \_______/|__/  \__/|_______/  \_______/ \____  $$ \_______/    \_/|__/|__/  |__/ \_______/   \___/  
#            /$$  | $$       /$$  \ $$                                                             /$$  | $$                                                   
#           |  $$$$$$/      |  $$$$$$/                                                            |  $$$$$$/                                                   
#            \______/        \______/                                                              \______/                                                    
