import logging
from logging.handlers import TimedRotatingFileHandler
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException, status, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from pydantic import BaseModel
from sqlalchemy import create_engine, text

# from fastapi.requests import Request

auth = HTTPBasic()

app = FastAPI(root_path="/api", dependencies=[Depends(auth)])

DATABASE_URL = "mysql+pymysql://admin:2!ecgRSV>QuiMN]@njara-candle-1.cdswweasecus.ap-south-1.rds.amazonaws.com:3306/trading_strategy"
# DATABASE_URL = "mysql+pymysql://admin:2!ecgRSV>QuiMN]@localhost:3307/trading_strategy"
DATABASE_ENGINE = create_engine(DATABASE_URL)

USERS = {'admin': {'password': 'njara_admin', 'api_key': '8561f1a2-51f6-44e0-a497-255dd336dd13'}}

app.add_middleware(
    CORSMiddleware,
    # allow_origins=["http://localhost:15243"],  # Replace with your React app's URL
    # allow_origins=["http://ec2-13-232-100-38.ap-south-1.compute.amazonaws.com"],  # Replace with your React app's URL
    allow_origins=["https://banjaronkidukan.work.gd"],  # Replace with your React app's URL
    allow_credentials=True,
    allow_methods=["put"],  # Allow all methods
    allow_headers=["*"]  # Allow all headers
)

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
fileHandler = TimedRotatingFileHandler(filename='token_update.log', when='D', interval=1)
fileHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s - %(lineno)d')
fileHandler.setFormatter(formatter)
log.addHandler(fileHandler)



def engine_connection():
    return DATABASE_ENGINE.connect()


class TokenRequest(BaseModel):
    api_key: str = None
    access_token: str


def basic_auth_verification(cred: HTTPBasicCredentials = Depends(auth)):
    log.info("Basic auth verification")
    user = cred.username
    sec_pass = cred.password
    if user in USERS and sec_pass == USERS[user]["password"]:
        print("User Validated")
        return user
    else:
        # From FastAPI
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email or password",
            headers={"WWW-Authenticate": "Basic"},
        )


@app.put("/update-token", status_code=status.HTTP_204_NO_CONTENT)
async def update_token(request_body: TokenRequest, accept_header: Annotated[str | None, Header(alias="Accept")] = None,
                       login_user=Depends(basic_auth_verification)):
    log.info("Received request to update token")
    if login_user:
        request_body.api_key = USERS[login_user]["api_key"]
        if accept_header != 'application/vnd.api.token+json.v1':
            raise HTTPException(status_code=406, detail="Unsupported Accept header")
        with engine_connection() as connection:
            stmt = text(
                'UPDATE upstox_configuration_details set access_token=:access_token, date_updated=NOW() WHERE api_key=:api_key')
            params = {'access_token': request_body.access_token, 'api_key': request_body.api_key}
            connection.execute(stmt, params)
            connection.commit()
        pass
