import pandas as pd
from fudstop.apis.polygonio.polygon_database import PolygonDatabase
db = PolygonDatabase()

class AllOptionsSDK:
    """master_all_two"""
    def __init__(self):
        self.call_attributes = [
        "call_change_eod",
        "call_ivbid",
        "call_iv_eod",
        "call_ivask",
        "call_days",
        "call_mean_eod",
        "call_ivint",
        "call_delta_eod",
        "call_bid_eod",
        "call_theoprice_eod",
        "call_ivint_eod",
        "call_ask_eod",
        "call_iv",
        "call_volume_eod",
        "call_bidtime",
        "call_rho",
        "call_forwardprice_eod",
        "call_mean",
        "call_bid",
        "call_volume",
        "call_alpha",
        "call_vega",
        "call_openinterest_eod",
        "call_asktime",
        "call_gamma_eod",
        "call_symbol",
        "call_paramvolapercent_eod",
        "call_asksize",
        "call_alpha_eod",
        "call_pos",
        "call_changepercent",
        "call_days_eod",
        "call_bidsize",
        "call_delta",
        "call_paramvolapercent_eod",
        "call_theta_eod",
        "call_change",
        "call_theta",
        "call_rho_eod",
        "call_forwardprice",
        "call_gamma",
        "call_changepercent_eod",
        "call_vega_eod",
        "call_theoprice"
    ]
        
        self.put_attributes = [
            "put_theta_eod",
            "put_asksize",
            "put_iv",
            "put_days",
            "put_iv_eod",
            "put_change_eod",
            "put_bid_eod",
            "put_ivint",
            "put_theoprice",
            "put_bidtime",
            "put_theta",
            "put_symbol",
            "put_ivask",
            "put_changepercent_eod",
            "put_ask",
            "put_rho",
            "put_ivint_eod",
            "put_bid",
            "put_ask_eod",
            "put_paramvolapercent_eod",
            "put_volume",
            "put_volume_eod",
            "put_ivbid",
            "put_delta_eod",
            "put_changepercent",
            "put_mean_eod",
            "put_asktime",
            "put_pos",
            "put_theoprice_eod",
            "put_gamma",
            "put_change",
            "put_vega",
            "put_days_eod",
            "put_forwardprice",
            "put_rho_eod",
            "put_vega_eod",
            "put_mean",
            "put_forwardprice_eod",
            "put_alpha_eod",
            "put_delta",
            "put_openinterest_eod",
            "put_gamma_eod",
            "put_bidsize",
            "put_alpha"
        ]


        self.greeks_attributes = [
            "vanna",
            "vomma",
            "charm",
            "veta",
            "speed",
            "zomma",
            "color",
            "ultima",
            "velocity",
            "sensitivity",
            "greeks_balance",
            "return_on_risk",
            "theta",
            "theta_decay_rate",
            "delta",
            "delta_theta_ratio",
            "gamma",
            "gamma_risk",
            "vega",
            "vega_impact"
        ]

        self.underlying_ivx_attributes = [
        "ivx7",
        "ivx14",
        "ivx21",
        "ivx30",
        "ivx60",
        "ivx90",
        "ivx120",
        "ivx150",
        "ivx180",
        "ivx270",
        "ivx360",
        "ivx720",
        "ivx1080",
        "ivx7_chg",
        "ivx14_chg",
        "ivx21_chg",
        "ivx30_chg",
        "ivx60_chg",
        "ivx90_chg",
        "ivx120_chg",
        "ivx150_chg",
        "ivx180_chg",
        "ivx270_chg",
        "ivx360_chg",
        "ivx720_chg",
        "ivx1080_chg",
        "ivx7_chg_percent",
        "ivx14_chg_percent",
        "ivx21_chg_percent",
        "ivx30_chg_percent",
        "ivx60_chg_percent",
        "ivx90_chg_percent",
        "ivx120_chg_percent",
        "ivx150_chg_percent",
        "ivx180_chg_percent",
        "ivx270_chg_percent",
        "ivx360_chg_percent",
        "ivx720_chg_percent",
        "ivx1080_chg_percent",
        "ivx7_chg_open",
        "ivx14_chg_open",
        "ivx21_chg_open",
        "ivx30_chg_open",
        "ivx60_chg_open",
        "ivx90_chg_open",
        "ivx120_chg_open",
        "ivx150_chg_open",
        "ivx180_chg_open",
        "ivx270_chg_open",
        "ivx360_chg_open",
        "ivx720_chg_open",
        "ivx1080_chg_open",
        "ivx7_chg_percent_open",
        "ivx14_chg_percent_open",
        "ivx21_chg_percent_open",
        "ivx30_chg_percent_open",
        "ivx60_chg_percent_open",
        "ivx90_chg_percent_open",
        "ivx120_chg_percent_open",
        "ivx150_chg_percent_open",
        "ivx180_chg_percent_open",
        "ivx270_chg_percent_open",
        "ivx360_chg_percent_open",
        "ivx720_chg_percent_open",
        "ivx1080_chg_percent_open"
    ]

        self.underlying_attributes = [
            "dividend_date",
            "dividend_amount",
            "dividend_frequency",
            "yield",
            "underlying_bid",
            "underlying_ask",
            "bid_ask_ratio",
            "underlying_mid",
            "underlying_bid_size",
            "underlying_ask_size",
            "opt_vol",
            "stock_vol",
            "change_to_breakeven",
            "underlying_price",
            "underlying_close",
            "underlying_open",
            "underlying_high",
            "underlying_low",
            "underlying_change_pct",
            "underlying_volume",
            "vibrate_ratio",
            "avg_vol_10d",
            "avg_vol_3m",
            "settlement_date",
            "short_interest",
            "average_volume",
            "days_to_cover",
            "pct_short",
            "underlying_avg_price",
            "total_num",
            "underlying_total_volume",
            "underlying_buy_volume",
            "underlying_sell_volume",
            "underlying_neutral_volume",
            "underlying_buy_pct",
            "underlying_sell_pct",
            "underlying_neutral_pct",
            "prev_close",
            "total_oi",
            "high_price_52wk",
            "low_price_52wk",
            "change",
            "change_percent",
            "change_open",
            "change_percent_open",
            "call_vol",
            "put_vol"
        ]

        self.contract_attributes = [
    "oi",
    "open",
    "high",
    "low",
    "close",
    "intrinsic_value",
    "extrinsic_value",
    "leverage_ratio",
    "vwap",
    "conditions",
    "price",
    "trade_size",
    "exchange",
    "ask",
    "bid",
    "spread",
    "spread_pct",
    "iv",
    "bid_size",
    "ask_size",
    "volume",
    "mid",
    "strike",
    "expiry",
    "dte",
    "time_value",
    "moneyness",
    "liquidity_score",
    "call_put",
    "change_ratio",
    "option_symbol",
    "opp",
    "velocity",
    "sensitivity",
    "profit_potential"
]

        self.underlying_volatility = [
        "hv10",
        "hv20",
        "hv30",
        "hv60",
        "hv90",
        "hv120",
        "hv150",
        "hv180",
        "hvp10",
        "hvp20",
        "hvp30",
        "hvp60",
        "hvp90",
        "hvp120",
        "hvp150",
        "hvp180",
        "beta10d",
        "beta20d",
        "beta30d",
        "beta60d",
        "beta90d",
        "beta120d",
        "beta150d",
        "beta180d",
        "beta_ratio",
        "corr10d",
        "corr20d",
        "corr30d",
        "corr60d",
        "corr90d",
        "corr120d",
        "corr150d",
        "corr180d",
        "volatile_rank",
        "ivp30",
        "ivp60",
        "ivp90",
        "ivr30",
        "ivr60",
        "ivr90",
        "ivr120",
        "ivr150",
        "ivr180",
        "iv_rank"
    ]
        self.technicals_attributes = [
            "rsi_day",
            "rsi_week",
            "rsi_month",
            "rsi_hour",
            "rsi_minute",
            "macd_day",
            "macd_hour",
            "macd_week",
            "macd_month",
            "td9_1hour",
            "td9_2hour",
            "td9_4hour",
            "td9_day",
            "td9_week",
            "td9_month"
        ]
        self.earnings_attributes  = [
    "total_assets",
    "total_current_assets",
    "cash_and_short_term_invest",
    "cash_equivalents",
    "short_term_investments",
    "total_receivables_net",
    "accounts_rece_trade_net",
    "total_inventory",
    "prepaid_expenses",
    "other_current_assets_total",
    "total_non_current_assets",
    "ppe_total_net",
    "ppe_total_gross",
    "accumulated_depreciation_total",
    "other_long_term_assets_total",
    "total_liabilities",
    "total_current_liabilities",
    "accounts_payable",
    "accrued_expenses",
    "notes_payable_short_term_debt",
    "current_portof_lt_debt_capital_leases",
    "total_non_current_liabilities",
    "total_long_term_debt",
    "long_term_debt",
    "total_debt",
    "other_liabilities_total",
    "total_equity",
    "total_stockhoders_equity",
    "common_stock",
    "additional_paid_in_capital",
    "retained_earnings",
    "other_equity_total",
    "total_liabilities_shareholders_equity",
    "total_common_shares_outstanding",
    "cashfrom_operating_activities",
    "net_income",
    "depreciation_and_amortization",
    "deferred_taxes",
    "non_cash_items",
    "changesin_working_capital",
    "cashfrom_investing_activities",
    "capital_expenditures",
    "other_investing_cash_flow_items_total",
    "cashfrom_financing_activities",
    "financing_cash_flow_items",
    "total_cash_dividends_paid",
    "issuance_retirementof_stock_net",
    "issuance_retirementof_debt_net",
    "foreign_exchange_effects",
    "net_changein_cash",
    "total_revenue",
    "revenue",
    "costof_revenue_total",
    "gross_profit",
    "operating_expense",
    "sell_gen_admin_expenses",
    "inter_expse_inc_net_oper",
    "unusual_expense_income",
    "operating_income",
    "inter_inc_expse_net_non_oper",
    "net_income_before_tax",
    "income_tax",
    "net_income_after_tax",
    "net_income_before_extra",
    "total_extraordinary_items",
    "income_avaito_com_excl_extra_ord",
    "income_avaito_com_incl_extra_ord",
    "diluted_net_income",
    "diluted_weighted_average_shares",
    "diluted_eps_excl_extra_items",
    "diluted_eps_incl_extra_items",
    "diluted_normalized_eps",
    "operating_profit",
    "earning_after_tax",
    "earning_before_tax",
    "eps",
    "pe",
    "earnings_yield"
]


    async def query(self, conditions: str):
        """Query the database using SQL and return a DataFrame."""
        await db.connect()
        # Ensure the database connection is established (assuming db.connect() is handled outside)
        # Define the base query
        base_query = "SELECT * FROM master_all_two"
        
        # Construct the full query by appending user conditions
        query = f"{base_query} WHERE {conditions}"
        
        print("Constructed SQL query:", query)
        
        try:
            # Fetch results from the database
            results = await db.fetch(query)
            
            # Fetch all column names from the table in the correct order
            column_query = """
            SELECT column_name
            FROM information_schema.columns
            WHERE table_name = 'master_all_two'
            ORDER BY ordinal_position
            """
            column_rows = await db.fetch(column_query)
            all_columns = [row['column_name'] for row in column_rows]
            
            # Debugging: print the number of columns and data returned
            print("Number of columns expected:", len(all_columns))
            if results:
                print("Number of columns in data:", len(results[0]))
            else:
                print("No data returned")
            
            # Ensure the number of columns matches the data
            if results and len(all_columns) != len(results[0]):
                raise ValueError(f"Mismatch between extracted columns ({len(all_columns)}) and data columns ({len(results[0])}).")
            
            # Create a DataFrame from the results
            df = pd.DataFrame(results, columns=all_columns)
            await db.disconnect()
            return df
        
        except Exception as e:
            print(f"An error occurred during the query: {str(e)}")
            return None