"""LVaR routes, mounted under /lvar. Every route requires the API key."""

import logging
import os
import re

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

from app.lvar.calculations.lvarCal import lvrCal
from app.lvar.database import (
    projectState_delete,
    projectState_init,
    rename_security_code_in_all_tables,
)
from app.lvar.helper import get_last_entry_from_sqlite
from app.lvar.storage.mkt_day_end import (
    get_mkt_day_end_data_from_sqlite,
    post_mkt_day_end_data_to_sqlite,
)
from app.lvar.storage.mkt_security import (
    get_mkt_security_from_sqlite,
    post_mkt_security_to_sqlite,
)
from app.security import (
    check_admin_credentials,
    project_delete_allowed,
    require_auth,
)

logger = logging.getLogger("lvar.router")

# Upper bound on list lengths in request bodies (sync.py sends batches of 20000).
MAX_LIST_ITEMS = int(os.getenv("MAX_REQUEST_LIST_ITEMS", "50000"))

# Security code format accepted by the rename endpoint.
SECURITY_CODE_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,64}$")

router = APIRouter(prefix="/lvar", tags=["lvar"], dependencies=[Depends(require_auth)])


# Pydantic model for the incoming data structure
class projectDataInit(BaseModel):
    status: int
    message: str
    data: list[dict] = Field(max_length=MAX_LIST_ITEMS)


class syncData(BaseModel):
    status: int
    message: str
    mde: list[dict] = Field(max_length=MAX_LIST_ITEMS)
    msi: list[dict] = Field(max_length=MAX_LIST_ITEMS)
    csh: list[dict] = Field(max_length=MAX_LIST_ITEMS)


@router.get("/get-last-entry")
def get_last_entry():
    result = get_last_entry_from_sqlite()
    return result


@router.post("/get-lvar-data")
def get_lvar_data(payload: syncData):
    result_mde = post_mkt_day_end_data_to_sqlite(payload.mde)
    result_msi = post_mkt_security_to_sqlite(payload.msi)

    if result_mde["status"] == 200 and result_msi["status"] == 200:
        try:
            result_lvrCal = lvrCal(payload.csh)
        except Exception:
            logger.exception("LVR calculation raised")
            return JSONResponse(
                status_code=500,
                content={"status": 500, "message": "LVR calculation failed"},
            )
        if result_lvrCal["status"] == 200:
            return {
                "status": 200,
                "message": "Data stored and LVR calculated successfully",
                "data": result_lvrCal,
            }
        else:
            return {
                "status": 500,
                "message": "LVR calculation failed",
            }
    else:
        return {
            "status": 500,
            "message": "Data stored failed",
            "mde": result_mde,
            "msi": result_msi,
        }


@router.get("/get-mkt-day-end-data/filter={filter_type}/{filter_value}")
def get_mkt_day_end_data(filter_type: str, filter_value: str):
    result = get_mkt_day_end_data_from_sqlite(filter_type, filter_value)

    reply_data = {
        "status": 200,
        "message": "Market day-end data retrieved successfully",
        "records_count": len(result),
        "data": result,
    }
    return reply_data


@router.get("/get-mkt-security-data")
def get_mkt_security_data():
    result = get_mkt_security_from_sqlite()
    reply_data = {
        "status": 200,
        "message": "Market security data retrieved successfully",
        "records_count": len(result),
        "data": result,
    }
    return reply_data


# project state related functions
# initialize the project state
@router.post("/project_init/{project_name}/{password}")
def project_init(project_name: str, password: str):
    if check_admin_credentials(project_name, password):
        result = projectState_init()
        if result:
            return {
                "message": "Project initialized successfully",
                "project_name": project_name,
            }
        else:
            return {
                "message": "Project initialization failed",
                "project_name": project_name,
            }
    else:
        return {"message": "Project not found or invalid credentials"}


# delete the project state
@router.post("/project_delete/{project_name}/{password}")
def project_delete(project_name: str, password: str):
    if check_admin_credentials(project_name, password):
        if not project_delete_allowed():
            logger.warning("project_delete refused: ALLOW_PROJECT_DELETE is not enabled")
            return {
                "message": "Project deletion failed",
                "project_name": project_name,
            }
        result = projectState_delete()
        if result:
            return {
                "message": "Project deleted successfully",
                "project_name": project_name,
            }
        else:
            return {
                "message": "Project deletion failed",
                "project_name": project_name,
            }
    else:
        return {"message": "Project not found or invalid credentials"}


@router.post("/project_data_init_mde")
def project_data_init(payload: projectDataInit):
    result = post_mkt_day_end_data_to_sqlite(payload.data)
    if result["status"] == 200:
        return {
            "message": "Project data initialized successfully",
            "data_count": result["data_count"],
        }
    else:
        return {
            "message": "Project data initialization failed",
            "data_count": result,
        }


@router.post("/project_data_init_msi")
def project_data_init_msi(payload: projectDataInit):
    result = post_mkt_security_to_sqlite(payload.data)
    if result["status"] == 200:
        return {
            "message": "Project security data initialized successfully",
            "data_count": result["data_count"],
        }
    else:
        return {
            "message": "Project security data initialization failed",
            "data_count": result,
        }


# Rename a security_code across all SQLite tables
@router.put("/rename-security-code/{old_code}/{new_code}")
def rename_security_code(old_code: str, new_code: str):
    """
    Rename *old_code* to *new_code* in every table that references security_code
    (mktSecurityInfo and mktDayEndData) inside a single atomic transaction.

    Example:
        PUT /lvar/rename-security-code/BATBC/BATBC_NEW
    """
    if not old_code or not new_code:
        return {"status": 400, "message": "Both old_code and new_code are required"}
    if old_code == new_code:
        return {"status": 400, "message": "old_code and new_code must be different"}
    if not SECURITY_CODE_RE.fullmatch(old_code) or not SECURITY_CODE_RE.fullmatch(new_code):
        return {
            "status": 400,
            "message": "old_code and new_code may only contain letters, digits, '_', '.', '-' (max 64 characters)",
        }

    result = rename_security_code_in_all_tables(old_code, new_code)
    return result

