from __future__ import annotations

from contextlib import asynccontextmanager
from importlib.util import find_spec
import ipaddress
import os
from pathlib import Path

from fastapi import Depends, FastAPI, HTTPException, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy import text
from sqlalchemy.orm import Session
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.middleware.gzip import GZipMiddleware

from .admin_audit import record_admin_event
from .admin_routes import router as admin_router
from .auth_routes import router as auth_router
from .calculation_artifacts import artifact_store
from .calculation_queue import CalculationDispatcher
from .calculation_resources import estimate_load_item_count, estimate_panel_load_item_count
from .calculation_routes import (
    JOB_SUBMIT_RATE_PER_MINUTE,
    MAX_ACTIVE_JOBS_PER_USER,
    MAX_JOB_ELEMENTS,
    MAX_JOB_LOAD_ITEMS,
    MAX_JOB_NODES,
    PUBLIC_CALCULATION_JOBS_ENABLED,
    router as calculation_router,
)
from .database import SessionLocal, get_db, init_database
from .isolated_solver import (
    SOLVE_MAX_CONCURRENT,
    SOLVE_TIMEOUT_SECONDS,
    SolverBusyError,
    SolverProcessError,
    SolverTimeoutError,
    solve_structure_isolated,
)
from .http_limits import RequestBodyLimitMiddleware
from .load_combination_routes import router as load_combination_router
from .models import User
from .member_design_routes import router as member_design_router
from .project_routes import router as project_router
from .release_metadata import APP_REVISION, APP_VERSION
from .section_profile_routes import router as section_profile_router
from .schemas import DemoModel, DemoSummary, SolveRequest, SolveResponse
from .security import (
    check_rate_limit,
    client_ip,
    ensure_csrf_cookie,
    get_admin_user,
    get_current_user,
    init_rate_limit_store,
    request_scheme,
    validate_csrf,
)
from .solver import demo_catalog, demo_request


def _env_bool(name: str, default: bool = False) -> bool:
    value = os.getenv(name)
    if value is None:
        return default
    normalized = value.strip().lower()
    if normalized in {"1", "true", "yes", "on"}:
        return True
    if normalized in {"0", "false", "no", "off"}:
        return False
    raise RuntimeError(f"{name} deve ser um booleano explicito (true/false).")


def _env_int(name: str, default: int) -> int:
    value = os.getenv(name)
    if value is None:
        return default
    try:
        parsed = int(value)
    except ValueError:
        return default
    return parsed if parsed > 0 else default


DOCS_ENABLED = _env_bool("FSE3D_DOCS_ENABLED", False)
MAX_VALIDATION_ERRORS_IN_RESPONSE = 200
calculation_dispatcher = CalculationDispatcher()


@asynccontextmanager
async def lifespan(app: FastAPI):
    init_database()
    init_rate_limit_store()
    artifact_store.initialize()
    calculation_dispatcher.start()
    try:
        yield
    finally:
        calculation_dispatcher.stop()


app = FastAPI(
    title="FSE3D",
    description="Aplicacao web para modelagem e analise estrutural 3D por elementos de barra.",
    version=APP_VERSION,
    lifespan=lifespan,
    docs_url="/docs" if DOCS_ENABLED else None,
    redoc_url="/redoc" if DOCS_ENABLED else None,
    openapi_url="/openapi.json" if DOCS_ENABLED else None,
)


@app.exception_handler(RequestValidationError)
async def sanitized_request_validation_error(
    request: Request,
    exc: RequestValidationError,
) -> JSONResponse:
    del request
    validation_errors = exc.errors()
    safe_errors = [
        {
            key: value
            for key, value in error.items()
            if key in {"type", "loc", "msg"}
        }
        for error in validation_errors[:MAX_VALIDATION_ERRORS_IN_RESPONSE]
    ]
    omitted = len(validation_errors) - len(safe_errors)
    if omitted > 0:
        safe_errors.append(
            {
                "type": "too_many_validation_errors",
                "loc": ["body"],
                "msg": f"{omitted} erro(s) adicional(is) omitido(s).",
            }
        )
    return JSONResponse(status_code=422, content={"detail": safe_errors})

STATIC_DIR = Path(__file__).resolve().parent / "static"


AUTH_REQUIRED = _env_bool("FSE3D_AUTH_REQUIRED", False)
FORCE_HTTPS = _env_bool("FSE3D_FORCE_HTTPS", True)
BOT_GUARD_ENABLED = _env_bool("FSE3D_BOT_GUARD_ENABLED", True)
MAX_SOLVE_NODES = _env_int("FSE3D_MAX_SOLVE_NODES", 500)
MAX_SOLVE_ELEMENTS = _env_int("FSE3D_MAX_SOLVE_ELEMENTS", 1000)
MAX_SOLVE_LOAD_ITEMS = _env_int("FSE3D_MAX_SOLVE_LOAD_ITEMS", 2000)
MAX_STIFFNESS_DOF = _env_int("FSE3D_MAX_STIFFNESS_DOF", 600)
MAX_SOLVE_WORK_UNITS = _env_int("FSE3D_MAX_SOLVE_WORK_UNITS", 150000)
MAX_REQUEST_BODY_BYTES = _env_int("FSE3D_MAX_REQUEST_BODY_BYTES", 32 * 1024 * 1024)
MAX_SYNC_SOLVE_REQUEST_BODY_BYTES = _env_int(
    "FSE3D_MAX_SYNC_SOLVE_REQUEST_BODY_BYTES",
    4 * 1024 * 1024,
)
SOLVE_RATE_LIMIT_PER_MINUTE = _env_int("FSE3D_SOLVE_RATE_LIMIT_PER_MINUTE", 30)
ALLOWED_HOSTS = [
    item.strip()
    for item in os.getenv(
        "FSE3D_ALLOWED_HOSTS",
        "fse3d.engfelix.com.br,localhost,127.0.0.1",
    ).split(",")
    if item.strip()
]
app.add_middleware(TrustedHostMiddleware, allowed_hosts=ALLOWED_HOSTS)
app.add_middleware(GZipMiddleware, minimum_size=500, compresslevel=6)
app.add_middleware(
    RequestBodyLimitMiddleware,
    max_bytes=MAX_REQUEST_BODY_BYTES,
    path_limits={"/api/solve": MAX_SYNC_SOLVE_REQUEST_BODY_BYTES},
)
app.include_router(auth_router)
app.include_router(admin_router)
app.include_router(project_router)
app.include_router(section_profile_router)
app.include_router(load_combination_router)
app.include_router(
    member_design_router,
    dependencies=[Depends(get_current_user)] if AUTH_REQUIRED else [],
)
app.include_router(calculation_router)
def _is_local_request(request: Request) -> bool:
    try:
        return ipaddress.ip_address(client_ip(request)).is_loopback
    except ValueError:
        return False


def _host_is_allowed(hostname: str) -> bool:
    normalized = hostname.rstrip(".").lower()
    for allowed in ALLOWED_HOSTS:
        pattern = allowed.rstrip(".").lower()
        if pattern == "*" or normalized == pattern:
            return True
        if pattern.startswith("*.") and normalized.endswith(pattern[1:]):
            return True
    return False


def _module_available(module_name: str) -> bool:
    try:
        return find_spec(module_name) is not None
    except (ImportError, ModuleNotFoundError, ValueError):
        return False


BLOCKED_USER_AGENT_TOKENS = (
    "${jndi",
    "bot",
    "crawler",
    "spider",
    "curl/",
    "python-requests",
    "scrapy",
    "go-http-client",
    "okhttp",
    "l9scan",
    "leakix",
    "censysinspect",
    "internetmeasurement",
    "tlm-audit-scanner",
    "palo alto networks",
    "cortex-xpanse",
    "greedyhand",
)

SUSPICIOUS_PATH_TOKENS = (
    "${jndi",
    "/.env",
    "/wp-",
    "/wordpress",
    "/xmlrpc.php",
    "/phpmyadmin",
    "/webadmin",
    "/webmail",
    "/sysinfo.cgi",
    "/tools.cgi",
    "/api/jsonws",
    "/mainframe.htm",
    "/artifactory",
    "/zentao",
    "/login_pic.asp",
    "/login.shtml",
    "/cgi-bin",
)

CONTENT_SECURITY_POLICY = (
    "default-src 'self'; "
    "script-src 'self' 'sha256-iuG7sMzvl/x6xC0pBpLDXDzdLIuvEw2TNwEu5tABPPA='; "
    "style-src 'self' 'unsafe-inline'; "
    "img-src 'self' data: blob:; "
    "font-src 'self' data:; "
    "connect-src 'self'; "
    "object-src 'none'; "
    "base-uri 'self'; "
    "form-action 'self'; "
    "frame-src 'none'; "
    "frame-ancestors 'none'"
)

SECURITY_HEADERS = {
    "Content-Security-Policy": CONTENT_SECURITY_POLICY,
    "X-Frame-Options": "DENY",
    "X-Content-Type-Options": "nosniff",
    "X-Permitted-Cross-Domain-Policies": "none",
    "Referrer-Policy": "same-origin",
    "Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
    "Cross-Origin-Opener-Policy": "same-origin",
    "Cross-Origin-Resource-Policy": "same-origin",
}


def _is_blocked_user_agent(user_agent: str) -> bool:
    normalized = user_agent.strip().lower()
    if not normalized:
        return False
    return any(token in normalized for token in BLOCKED_USER_AGENT_TOKENS)


def _is_suspicious_probe_target(request: Request) -> bool:
    target = request.url.path.lower()
    if request.url.query:
        target = f"{target}?{request.url.query.lower()}"
    if target == "/robots.txt":
        return False
    return any(token in target for token in SUSPICIOUS_PATH_TOKENS)


def _apply_security_headers(response: Response, scheme: str) -> Response:
    response.headers.setdefault("X-Robots-Tag", "noindex, nofollow")
    if scheme == "https":
        response.headers.setdefault("Strict-Transport-Security", "max-age=31536000")
    for header_name, header_value in SECURITY_HEADERS.items():
        response.headers.setdefault(header_name, header_value)
    return response


@app.middleware("http")
async def enforce_https(request: Request, call_next):
    scheme = request_scheme(request)
    request_hostname = (request.url.hostname or "").lower()
    if not _host_is_allowed(request_hostname):
        return _apply_security_headers(PlainTextResponse("Invalid host", status_code=400), scheme)
    is_local = _is_local_request(request)
    content_length = request.headers.get("content-length")
    if content_length:
        try:
            if int(content_length) > MAX_REQUEST_BODY_BYTES:
                return _apply_security_headers(
                    PlainTextResponse("Request body too large", status_code=413),
                    scheme,
                )
        except ValueError:
            return _apply_security_headers(
                PlainTextResponse("Invalid Content-Length", status_code=400),
                scheme,
            )

    if BOT_GUARD_ENABLED and not is_local:
        if _is_suspicious_probe_target(request):
            return _apply_security_headers(PlainTextResponse("Not Found", status_code=404), scheme)
        if request.url.path != "/robots.txt" and _is_blocked_user_agent(request.headers.get("user-agent", "")):
            return _apply_security_headers(PlainTextResponse("Forbidden", status_code=403), scheme)

    if FORCE_HTTPS and scheme == "http" and not is_local:
        url = str(request.url).replace("http://", "https://", 1)
        return _apply_security_headers(RedirectResponse(url, status_code=308), scheme)

    response = await call_next(request)
    if request.url.path.startswith(("/static/mapadoprojeto/", "/static/administracao/")):
        response.headers["Cache-Control"] = "private, no-store, no-cache, must-revalidate"
        response.headers["Pragma"] = "no-cache"
        response.headers["Expires"] = "0"
        response.headers["Vary"] = "Cookie"
    elif request.url.path.startswith("/static/"):
        if request.query_params.get("v") or request.url.path.startswith("/static/vendor/"):
            response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
            if "Pragma" in response.headers:
                del response.headers["Pragma"]
            if "Expires" in response.headers:
                del response.headers["Expires"]
        else:
            response.headers["Cache-Control"] = "no-cache"
    elif (
        request.url.path in {
            "/",
            "/r12",
            "/r12/",
            "/projeto",
            "/projeto/",
            "/mapadoprojeto",
            "/mapadoprojeto/",
            "/administracao",
            "/administracao/",
            "/manual",
            "/manual/",
            "/reasonofthis",
            "/reasonofthis/",
            "/robots.txt",
        }
        or request.url.path.startswith("/api/")
    ):
        response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
        response.headers["Pragma"] = "no-cache"
        response.headers["Expires"] = "0"
    return _apply_security_headers(response, scheme)


@app.get("/")
def read_index() -> FileResponse:
    return FileResponse(STATIC_DIR / "index.html")


@app.get("/reasonofthis", include_in_schema=False)
@app.head("/reasonofthis", include_in_schema=False)
@app.get("/reasonofthis/", include_in_schema=False)
@app.head("/reasonofthis/", include_in_schema=False)
def redirect_current_tribute() -> RedirectResponse:
    return RedirectResponse("https://engfelix.com.br/", status_code=308)


@app.get("/reasonofthis/historic", include_in_schema=False)
@app.head("/reasonofthis/historic", include_in_schema=False)
@app.get("/reasonofthis/historic/", include_in_schema=False)
@app.head("/reasonofthis/historic/", include_in_schema=False)
def redirect_tribute_history() -> RedirectResponse:
    return RedirectResponse("https://engfelix.com.br/historic/", status_code=308)


@app.get("/reasonofthis/dia_dos_namorados_2026", include_in_schema=False)
@app.head("/reasonofthis/dia_dos_namorados_2026", include_in_schema=False)
@app.get("/reasonofthis/dia_dos_namorados_2026/", include_in_schema=False)
@app.head("/reasonofthis/dia_dos_namorados_2026/", include_in_schema=False)
@app.get("/r12", include_in_schema=False)
@app.head("/r12", include_in_schema=False)
@app.get("/r12/", include_in_schema=False)
@app.head("/r12/", include_in_schema=False)
def redirect_valentines_tribute() -> RedirectResponse:
    return RedirectResponse(
        "https://engfelix.com.br/historic/dia_dos_namorados_2026/",
        status_code=308,
    )


@app.get("/projeto", include_in_schema=False)
@app.get("/projeto/", include_in_schema=False)
def read_project_report() -> FileResponse:
    return FileResponse(STATIC_DIR / "projeto" / "index.html")


@app.get("/mapadoprojeto", include_in_schema=False)
@app.get("/mapadoprojeto/", include_in_schema=False)
def read_project_map(
    request: Request,
    admin: User = Depends(get_admin_user),
    db: Session = Depends(get_db),
) -> FileResponse:
    record_admin_event(
        db,
        request,
        actor=admin,
        action="project_map_viewed",
        resource="project_map",
    )
    db.commit()
    return FileResponse(STATIC_DIR / "mapadoprojeto" / "index.html")


PROJECT_MAP_ASSETS = frozenset(
    {
        "index.html",
        "map-data.json",
        "mapadoprojeto.css",
        "mapadoprojeto.js",
    }
)


@app.get("/static/mapadoprojeto/{asset_path:path}", include_in_schema=False)
def read_project_map_asset(
    asset_path: str,
    _admin: User = Depends(get_admin_user),
) -> FileResponse:
    if asset_path not in PROJECT_MAP_ASSETS:
        raise HTTPException(status_code=404, detail="Arquivo nao encontrado.")
    return FileResponse(STATIC_DIR / "mapadoprojeto" / asset_path)


ADMIN_PANEL_ASSETS = frozenset(
    {
        "administracao.css",
        "administracao.js",
        "index.html",
    }
)


@app.get("/administracao", include_in_schema=False)
@app.get("/administracao/", include_in_schema=False)
def read_admin_panel(
    request: Request,
    admin: User = Depends(get_admin_user),
    db: Session = Depends(get_db),
) -> FileResponse:
    record_admin_event(
        db,
        request,
        actor=admin,
        action="admin_panel_viewed",
        resource="admin_panel",
    )
    db.commit()
    return FileResponse(STATIC_DIR / "administracao" / "index.html")


@app.get("/static/administracao/{asset_path:path}", include_in_schema=False)
def read_admin_panel_asset(
    asset_path: str,
    _admin: User = Depends(get_admin_user),
) -> FileResponse:
    if asset_path not in ADMIN_PANEL_ASSETS:
        raise HTTPException(status_code=404, detail="Arquivo nao encontrado.")
    return FileResponse(STATIC_DIR / "administracao" / asset_path)


@app.get("/manual", include_in_schema=False)
@app.get("/manual/", include_in_schema=False)
def read_user_manual() -> FileResponse:
    return FileResponse(STATIC_DIR / "manual" / "index.html")


@app.get("/robots.txt", response_class=PlainTextResponse)
def robots_txt() -> str:
    return "\n".join([
        "User-agent: *",
        "Disallow: /api/",
        "Disallow: /static/",
        "Disallow: /projects/",
        "Disallow: /auth/",
        "",
    ])


@app.get("/api/health")
def health() -> dict:
    checks = {"database": False, "openseespy": _module_available("openseespy.opensees")}
    try:
        with SessionLocal() as db:
            db.execute(text("SELECT 1"))
        checks["database"] = True
    except Exception:
        checks["database"] = False
    if not all(checks.values()):
        raise HTTPException(status_code=503, detail={"status": "degraded", "checks": checks})
    return {"status": "ok", "checks": checks}


@app.get("/api/config")
def app_config(request: Request, response: Response) -> dict:
    ensure_csrf_cookie(response, request)
    return {
        "revision": APP_REVISION,
        "version": APP_VERSION,
        "auth_required": AUTH_REQUIRED,
        "docs_enabled": DOCS_ENABLED,
        "max_solve_nodes": MAX_SOLVE_NODES,
        "max_solve_elements": MAX_SOLVE_ELEMENTS,
        "max_solve_load_items": MAX_SOLVE_LOAD_ITEMS,
        "max_stiffness_dof": MAX_STIFFNESS_DOF,
        "max_solve_work_units": MAX_SOLVE_WORK_UNITS,
        "max_sync_solve_request_body_bytes": MAX_SYNC_SOLVE_REQUEST_BODY_BYTES,
        "solve_rate_limit_per_minute": SOLVE_RATE_LIMIT_PER_MINUTE,
        "solve_timeout_seconds": SOLVE_TIMEOUT_SECONDS,
        "solve_max_concurrent": SOLVE_MAX_CONCURRENT,
        "calculation_jobs_enabled": True,
        "public_calculation_jobs_enabled": PUBLIC_CALCULATION_JOBS_ENABLED,
        "max_job_nodes": MAX_JOB_NODES,
        "max_job_elements": MAX_JOB_ELEMENTS,
        "max_job_load_items": MAX_JOB_LOAD_ITEMS,
        "max_active_jobs_per_user": MAX_ACTIVE_JOBS_PER_USER,
        "job_submit_rate_per_minute": JOB_SUBMIT_RATE_PER_MINUTE,
        "solver_engines": [
            {"id": "openseespy", "status": "available", "label": "OpenSees"},
            {"id": "pynite", "status": "future", "label": "PyNite"},
            {"id": "native_truss", "status": "future", "label": "Motor proprio"},
        ],
        "analysis_modes": [
            {"id": "characteristic", "status": "available", "label": "Carregamento caracteristico"},
            {"id": "manual", "status": "available", "label": "Combinacao manual rastreavel"},
            {"id": "nbr_8681_2025", "status": "available", "label": "Combinacoes ABNT NBR 8681:2025"},
        ],
    }


@app.get("/api/demos", response_model=list[DemoSummary])
def read_demos() -> list[DemoSummary]:
    return demo_catalog()


@app.get("/api/demos/{demo_id}", response_model=DemoModel)
def read_demo_by_id(demo_id: str) -> DemoModel:
    try:
        return demo_request(demo_id)
    except ValueError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc


@app.get("/api/demo", response_model=DemoModel)
def read_demo() -> DemoModel:
    return demo_request()


def _load_item_count(request: SolveRequest) -> int:
    return estimate_load_item_count(request)


def _enforce_solve_limits(request: SolveRequest) -> None:
    if len(request.nodes) > MAX_SOLVE_NODES:
        raise HTTPException(
            status_code=413,
            detail=(
                "Modelo com muitos nos para calculo pela API "
                f"({len(request.nodes)} nos; limite {MAX_SOLVE_NODES})."
            ),
        )
    if len(request.elements) > MAX_SOLVE_ELEMENTS:
        raise HTTPException(
            status_code=413,
            detail=(
                "Modelo com muitas barras para calculo pela API "
                f"({len(request.elements)} barras; limite {MAX_SOLVE_ELEMENTS})."
            ),
        )
    load_items = _load_item_count(request)
    if load_items > MAX_SOLVE_LOAD_ITEMS:
        raise HTTPException(
            status_code=413,
            detail=(
                "Modelo com muitas cargas para calculo pela API "
                f"({load_items} cargas; limite {MAX_SOLVE_LOAD_ITEMS})."
            ),
        )

    work_units = (
        len(request.nodes) * 6
        + len(request.elements) * max(request.diagram_points, 101)
        + (
            len(request.member_distributed_loads)
            + estimate_panel_load_item_count(request)
        ) * 24
        + load_items * 2
    )
    if work_units > MAX_SOLVE_WORK_UNITS:
        raise HTTPException(
            status_code=413,
            detail=(
                "Modelo excede o orcamento seguro de processamento e resposta "
                f"({work_units} unidades; limite {MAX_SOLVE_WORK_UNITS})."
            ),
        )


def _solve_request(request: SolveRequest) -> SolveResponse:
    _enforce_solve_limits(request)
    estimated_dof_count = len(request.nodes) * 6
    if request.include_stiffness_matrix and estimated_dof_count > MAX_STIFFNESS_DOF:
        raise HTTPException(
            status_code=400,
            detail=(
                "Matriz de rigidez muito grande para retorno pela API "
                f"({estimated_dof_count} GDL estimados; limite {MAX_STIFFNESS_DOF}). "
                "Desative a matriz completa ou aumente FSE3D_MAX_STIFFNESS_DOF com cuidado."
            ),
        )
    try:
        return solve_structure_isolated(request)
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc
    except SolverBusyError as exc:
        raise HTTPException(status_code=503, detail=str(exc), headers={"Retry-After": "2"}) from exc
    except SolverTimeoutError as exc:
        raise HTTPException(status_code=504, detail=str(exc)) from exc
    except SolverProcessError as exc:
        raise HTTPException(status_code=500, detail=str(exc)) from exc


if AUTH_REQUIRED:
    @app.post("/api/solve", response_model=SolveResponse)
    def solve(
        payload: SolveRequest,
        http_request: Request,
        current_user: User = Depends(get_current_user),
    ) -> SolveResponse:
        validate_csrf(http_request)
        check_rate_limit(http_request, "solve", SOLVE_RATE_LIMIT_PER_MINUTE, 60)
        return _solve_request(payload)
else:
    @app.post("/api/solve", response_model=SolveResponse)
    def solve(payload: SolveRequest, http_request: Request) -> SolveResponse:
        check_rate_limit(http_request, "solve", SOLVE_RATE_LIMIT_PER_MINUTE, 60)
        return _solve_request(payload)


app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
