from AppCode.Config import DBConfig
import mysql.connector
import pandas as pd
import io




class AOHandler:

    def __init__(self):
        self.conn = DBConfig.get_db_connection()
        self.cursor = self.conn.cursor(dictionary=True)
        
    # GET ALL AO RECORDS using stored procedure "GetAllItr"
    def get_all_ao(self):
        self.cursor.callproc("GetAllAO")
        records = []

        for result in self.cursor.stored_results():
            records = result.fetchall()

        return records


    def get_ao_by_id(self, id):
        # Call stored procedure
        self.cursor.callproc('GetAOById', [id])
        # Fetch result
        records = []
        for result in self.cursor.stored_results():
            records = result.fetchall()

        if records:
            return records[0]  # return single record
           
        return None

        """  variable of AO model
        year, gross_total_income, disallowance_14a, disallowance_37,
        deduction_80ia_business, deduction_sec37_disallowance, deduction_80g,
        net_taxable_income, tax_30_percent, tax_book_profit_18_5,
        surcharge_12, edu_cess_3, total_tax_payable, mat_credit,
        interest_234c, total_tax, advance_tax, tds, tcs,
        tax_on_assessment, refund
        
        """


    def add_ao(self, data):
            fields = [
                "year","gross_total_income", "disallowance_14a", "disallowance_37",
                "deduction_80ia_business", "deduction_sec37_disallowance", "deduction_80g",
                "net_taxable_income", "tax_30_percent", "tax_book_profit_18_5",
                "surcharge_12", "edu_cess_3", "total_tax_payable", "mat_credit",
                "interest_234c", "total_tax", "advance_tax", "tds", "tcs",
                "tax_on_assessment", "refund","Remarks"
            ]

            values = [data.get(f, 0) for f in fields]
            print("---- values ---- ",values)

            self.cursor.callproc("InsertAO", values)
            self.conn.commit()

    
    # UPDATE ITR RECORD by AO id
    def update_ao(self, id, data):

        fields = [
            "year","gross_total_income", "disallowance_14a", "disallowance_37",
            "deduction_80ia_business", "deduction_sec37_disallowance", "deduction_80g",
            "net_taxable_income", "tax_30_percent", "tax_book_profit_18_5",
            "surcharge_12", "edu_cess_3", "total_tax_payable", "mat_credit",
            "interest_234c", "total_tax", "advance_tax", "tds", "tcs",
            "tax_on_assessment", "refund","Remarks"
        ]

        values = [id] + [data.get(f, 0) for f in fields]

        print("AO update values:", values)  

        self.cursor.callproc("UpdateAOById", values)
        self.conn.commit()


    # DELETE RECORD by AO id
    def delete_ao_by_id(self, id):
        # Call the stored procedure
        self.cursor.callproc('DeleteAOById', [id])
        self.conn.commit()


    # CLOSE CONNECTION
    def close(self):
        self.cursor.close()
        self.conn.close()

    def ao_report_download(self, selected_year):
            try:
                # Call stored proc to fetch year-wise records
                self.cursor.callproc("GetAOByYear", [selected_year])

                rows = []
                for result in self.cursor.stored_results():
                    rows = result.fetchall()

                if not rows:
                    return None

                df = pd.DataFrame(rows)

                # TRANSPOSE
                df_transposed = df.transpose()
                df_transposed.insert(0, 'Field', df_transposed.index)

                # Rename columns: Record 1, 2, 3...
                record_cols = {
                    i: f"Record {i}"
                    for i in df_transposed.columns if isinstance(i, int)
                }
                df_transposed.rename(columns=record_cols, inplace=True)
                df_transposed.reset_index(drop=True, inplace=True)

                # Excel Output
                output = io.BytesIO()
                with pd.ExcelWriter(output, engine="xlsxwriter") as writer:
                    df_transposed.to_excel(writer, index=False, sheet_name="AO_Vertical")
                    worksheet = writer.sheets["AO_Vertical"]
                    worksheet.set_column(0, 0, 30)

                output.seek(0)
                return output

            except mysql.connector.Error as e:
                print("MySQL Error:", e)
                return None