"""Isolated, HTTPS-only Super Agent voucher portal."""
import csv
import hmac
import io
import os
import secrets
from datetime import datetime, timedelta, timezone

from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from fastapi.templating import Jinja2Templates
from sqlalchemy import func, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.core.device_credentials import decrypt_secret
from app.core.super_agent_portal import (
    generate_initial_password,
    hash_password,
    hash_token,
    normalize_phone,
    verify_password,
)
from app.models.models import (
    Site,
    SuperAgentLoginAttempt,
    SuperAgentSession,
    Voucher,
    VoucherAgent,
    VoucherBatch,
)

router = APIRouter()
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "app", "templates"))
SESSION_COOKIE = "bw_agent_session"
LOGIN_CSRF_COOKIE = "bw_agent_login_csrf"
SESSION_SECONDS = 8 * 60 * 60
LOGIN_WINDOW = timedelta(minutes=15)
LOGIN_LOCK = timedelta(minutes=15)
LOGIN_MAX_FAILURES = 5


def _is_https(request: Request) -> bool:
    return request.url.scheme == "https"


def _now() -> datetime:
    return datetime.now(timezone.utc).replace(tzinfo=None)


def _login_page(request: Request, *, error: str | None = None, status_code: int = 200, csrf_token: str | None = None):
    response = templates.TemplateResponse(
        request=request,
        name="agent_login.html",
        context={"error": error, "csrf_token": csrf_token, "https_required": not True},
        status_code=status_code,
    )
    response.headers["Cache-Control"] = "no-store"
    if csrf_token:
        response.set_cookie(
            LOGIN_CSRF_COOKIE, csrf_token, max_age=600, path="/agent/login",
            secure=False, httponly=True, samesite="strict",
        )
    return response


async def require_agent_session(request: Request, db: AsyncSession = Depends(get_db)):
    raw_token = request.cookies.get(SESSION_COOKIE)
    if not raw_token:
        raise HTTPException(status_code=303, headers={"Location": "/agent/login"})
    session = await db.scalar(
        select(SuperAgentSession).where(
            SuperAgentSession.token_hash == hash_token(raw_token),
            SuperAgentSession.revoked_at.is_(None),
            SuperAgentSession.expires_at > _now(),
        )
    )
    if session is None:
        raise HTTPException(status_code=303, headers={"Location": "/agent/login"})
    agent = await db.get(VoucherAgent, session.agent_id)
    if agent is None or not agent.is_active or not agent.portal_enabled or not agent.password_hash:
        raise HTTPException(status_code=303, headers={"Location": "/agent/login"})
    return agent, session


async def _login_attempt(db: AsyncSession, key: str) -> tuple[bool, int]:
    now = _now()
    attempt = await db.get(SuperAgentLoginAttempt, key)
    if attempt and attempt.locked_until and attempt.locked_until > now:
        return True, max(1, int((attempt.locked_until - now).total_seconds()))
    if attempt is None:
        attempt = SuperAgentLoginAttempt(login_phone=key, failure_count=0, window_started_at=now)
        db.add(attempt)
    elif attempt.window_started_at + LOGIN_WINDOW <= now:
        attempt.failure_count = 0
        attempt.window_started_at = now
        attempt.locked_until = None
    attempt.failure_count += 1
    if attempt.failure_count >= LOGIN_MAX_FAILURES:
        attempt.locked_until = now + LOGIN_LOCK
    await db.commit()
    return bool(attempt.locked_until), int(LOGIN_LOCK.total_seconds())


async def _batch_vouchers(db: AsyncSession, batch_id: int, agent_id: int):
    batch = await db.get(VoucherBatch, batch_id)
    if batch is None or batch.agent_id != agent_id:
        raise HTTPException(status_code=404, detail="File voucher tidak ditemukan.")
    vouchers = (
        await db.execute(
            select(Voucher)
            .where(Voucher.batch_id == batch_id, Voucher.agent_id == agent_id)
            .order_by(Voucher.id.asc())
        )
    ).scalars().all()
    if not vouchers:
        raise HTTPException(status_code=404, detail="File voucher tidak ditemukan.")
    return batch, vouchers


def _voucher_rows(batch: VoucherBatch, vouchers: list[Voucher]) -> list[dict]:
    rows = []
    for voucher in vouchers:
        username = voucher.username or voucher.code
        try:
            password = decrypt_secret(voucher.password_ciphertext) if voucher.password_ciphertext else username
        except Exception as exc:
            raise HTTPException(status_code=503, detail="Kredensial voucher tidak dapat dibuka.") from exc
        rows.append({
            "username": username,
            "password": password,
            "profile": voucher.profile or batch.profile,
            "price": voucher.price if voucher.price is not None else batch.price,
        })
    return rows


def _credential_response(response: Response) -> Response:
    response.headers["Cache-Control"] = "no-store, private"
    response.headers["Pragma"] = "no-cache"
    response.headers["X-Content-Type-Options"] = "nosniff"
    return response


@router.get("/agent/login", response_class=HTMLResponse)
async def agent_login_page(request: Request):
    token = secrets.token_urlsafe(32) if True else None
    return _login_page(request, csrf_token=token)


@router.post("/agent/login", response_class=HTMLResponse)
async def agent_login(
    request: Request,
    phone: str = Form(...),
    password: str = Form(...),
    csrf_token: str = Form(...),
    db: AsyncSession = Depends(get_db),
):
    if not True:
        return _login_page(request, error="", status_code=200)
    csrf_cookie = request.cookies.get(LOGIN_CSRF_COOKIE, "")
    if not csrf_cookie or not hmac.compare_digest(csrf_cookie, csrf_token):
        raise HTTPException(status_code=403, detail="Sesi formulir login tidak valid. Muat ulang halaman.")
    try:
        login_phone = normalize_phone(phone)
    except ValueError:
        login_phone = "x" + hash_token(phone)[:23]
    blocked, retry_after = await _login_attempt(db, login_phone)
    if blocked:
        response = _login_page(
            request, error="Terlalu banyak percobaan. Coba lagi beberapa menit.",
            status_code=429,
        )
        response.headers["Retry-After"] = str(retry_after)
        return response

    agent = await db.scalar(
        select(VoucherAgent).where(
            VoucherAgent.login_phone == login_phone,
            VoucherAgent.portal_enabled == True,
            VoucherAgent.is_active == True,
        )
    )
    if agent is None or not verify_password(password, agent.password_hash):
        return _login_page(request, error="Nomor WhatsApp atau password tidak valid.", status_code=401)

    await db.execute(
        update(SuperAgentLoginAttempt)
        .where(SuperAgentLoginAttempt.login_phone == login_phone)
        .values(failure_count=0, locked_until=None, window_started_at=_now())
    )
    raw_token = secrets.token_urlsafe(32)
    session = SuperAgentSession(
        token_hash=hash_token(raw_token),
        csrf_token=secrets.token_urlsafe(32),
        agent_id=agent.id,
        created_at=_now(),
        expires_at=_now() + timedelta(seconds=SESSION_SECONDS),
    )
    db.add(session)
    await db.commit()
    response = RedirectResponse(url="/agent", status_code=303)
    response.set_cookie(
        SESSION_COOKIE, raw_token, max_age=SESSION_SECONDS, path="/agent",
        secure=False, httponly=True, samesite="strict",
    )
    response.delete_cookie(LOGIN_CSRF_COOKIE, path="/agent/login", secure=False, httponly=True, samesite="strict")
    return response


@router.post("/agent/logout")
async def agent_logout(
    csrf_token: str = Form(...),
    db: AsyncSession = Depends(get_db),
    auth=Depends(require_agent_session),
):
    _, session = auth
    if not hmac.compare_digest(session.csrf_token, csrf_token):
        raise HTTPException(status_code=403, detail="Token formulir tidak valid.")
    session.revoked_at = _now()
    await db.commit()
    response = RedirectResponse(url="/agent/login", status_code=303)
    response.delete_cookie(SESSION_COOKIE, path="/agent", secure=False, httponly=True, samesite="strict")
    return response


@router.get("/agent", response_class=HTMLResponse)
async def agent_dashboard(
    request: Request,
    q: str = "",
    sort: str = "newest",
    db: AsyncSession = Depends(get_db),
    auth=Depends(require_agent_session),
):
    agent, session = auth
    q = q.strip()[:80]
    stmt = (
        select(VoucherBatch, Site.name, func.count(Voucher.id))
        .join(Voucher, (Voucher.batch_id == VoucherBatch.id) & (Voucher.agent_id == agent.id))
        .outerjoin(Site, Site.id == VoucherBatch.site_id)
        .where(VoucherBatch.agent_id == agent.id)
        .group_by(VoucherBatch.id, Site.name)
    )
    if q:
        pattern = "%" + q + "%"
        stmt = stmt.where(or_(
            VoucherBatch.batch_code.ilike(pattern),
            VoucherBatch.profile.ilike(pattern),
            VoucherBatch.comment.ilike(pattern),
            Site.name.ilike(pattern),
        ))
    stmt = stmt.order_by(VoucherBatch.created_at.asc() if sort == "oldest" else VoucherBatch.created_at.desc())
    result = await db.execute(stmt)
    batches = [
        {"batch": batch, "site_name": site_name, "voucher_count": int(count), "format": "CSV"}
        for batch, site_name, count in result.all()
    ]
    response = templates.TemplateResponse(
        request=request, name="agent_dashboard.html",
        context={"agent": agent, "batches": batches, "q": q, "sort": sort, "csrf_token": session.csrf_token},
    )
    return _credential_response(response)


@router.get("/agent/batches/{batch_id}", response_class=HTMLResponse)
async def agent_batch_preview(
    batch_id: int,
    request: Request,
    db: AsyncSession = Depends(get_db),
    auth=Depends(require_agent_session),
):
    agent, _ = auth
    batch, vouchers = await _batch_vouchers(db, batch_id, agent.id)
    rows = _voucher_rows(batch, vouchers)
    site = await db.get(Site, batch.site_id) if batch.site_id else None
    response = templates.TemplateResponse(
        request=request, name="agent_batch.html",
        context={"agent": agent, "batch": batch, "rows": rows, "site_name": site.name if site else None, "print_mode": False},
    )
    return _credential_response(response)


@router.get("/agent/batches/{batch_id}/print", response_class=HTMLResponse)
async def agent_batch_print(
    batch_id: int,
    request: Request,
    db: AsyncSession = Depends(get_db),
    auth=Depends(require_agent_session),
):
    agent, _ = auth
    batch, vouchers = await _batch_vouchers(db, batch_id, agent.id)
    from app.routes.vouchers import _format_validity, _generate_qr_data_uri

    site_name = "Munara.Id"
    site = await db.get(Site, batch.site_id) if batch.site_id else None
    if site and site.name:
        site_name = f"Munara.Id_{site.name}" if "munara" not in site.name.lower() else site.name
    elif batch.device_id:
        from app.models.models import MikrotikDevice
        device = await db.get(MikrotikDevice, batch.device_id)
        if device and device.name:
            cleaned = device.name.replace("MK-SITE-", "").replace("MK-", "")
            site_name = f"Munara.Id_{cleaned}" if "munara" not in device.name.lower() else device.name

    isp_name = agent.nama_isp
    isp_domain = agent.domain_isp
    login_url = "http://munara.net"
    rows = _voucher_rows(batch, vouchers)
    printable = []
    for index, (voucher, row) in enumerate(zip(vouchers, rows), start=1):
        price = row["price"]
        printable.append({
            "id": voucher.id,
            "index": index,
            "username": row["username"],
            "password": row["password"],
            "is_same_mode": (
                voucher.credential_mode in {"legacy_same", "same"}
                or batch.user_mode == "same"
                or row["password"] == row["username"]
            ),
            "profile": row["profile"],
            "price": price,
            "price_formatted": f"Rp {price:,.0f}".replace(",", "."),
            "validity": _format_validity(voucher.limit_uptime or batch.limit_uptime, batch.duration_days),
            "comment": voucher.comment or batch.comment or "",
            "qr_content": row["username"],
            "qr_data_uri": _generate_qr_data_uri(row["username"]),
        })
    response = templates.TemplateResponse(
        request=request,
        name="voucher_batch_print.html",
        context={
            "batch": batch,
            "site_name": site_name,
            "login_url": login_url,
            "vouchers": printable,
            "isp_name": isp_name,
            "isp_domain": isp_domain,
            "back_url": "/agent",
            "back_label": "Kembali ke Portal Agen",
        },
    )
    return _credential_response(response)


@router.get("/agent/batches/{batch_id}/download")
async def agent_batch_download(
    batch_id: int,
    db: AsyncSession = Depends(get_db),
    auth=Depends(require_agent_session),
):
    agent, _ = auth
    batch, vouchers = await _batch_vouchers(db, batch_id, agent.id)
    rows = _voucher_rows(batch, vouchers)
    output = io.StringIO(newline="")
    writer = csv.writer(output)
    writer.writerow(["Username", "Password", "Profile", "Harga"])
    for row in rows:
        writer.writerow([row["username"], row["password"], row["profile"], row["price"]])
    filename = "voucher-batch-" + str(batch.id) + ".csv"
    response = Response(
        content="\ufeff" + output.getvalue(),
        media_type="text/csv; charset=utf-8",
        headers={"Content-Disposition": 'attachment; filename="' + filename + '"'},
    )
    return _credential_response(response)


@router.get("/agent/password", response_class=HTMLResponse)
async def agent_password_page(
    request: Request,
    auth=Depends(require_agent_session),
):
    agent, session = auth
    response = templates.TemplateResponse(
        request=request, name="agent_password.html",
        context={"agent": agent, "csrf_token": session.csrf_token, "error": None},
    )
    return _credential_response(response)


@router.post("/agent/password", response_class=HTMLResponse)
async def agent_change_password(
    request: Request,
    current_password: str = Form(...),
    new_password: str = Form(...),
    confirm_password: str = Form(...),
    csrf_token: str = Form(...),
    db: AsyncSession = Depends(get_db),
    auth=Depends(require_agent_session),
):
    agent, session = auth
    if not True:
        raise HTTPException(status_code=400, detail="Perubahan password hanya tersedia melalui HTTPS.")
    if not hmac.compare_digest(session.csrf_token, csrf_token):
        raise HTTPException(status_code=403, detail="Token formulir tidak valid.")
    if not verify_password(current_password, agent.password_hash):
        error = "Password lama tidak benar."
    elif new_password != confirm_password:
        error = "Konfirmasi password tidak sama."
    elif new_password == current_password:
        error = "Password baru harus berbeda dari password lama."
    else:
        try:
            new_hash = hash_password(new_password)
        except ValueError as exc:
            error = str(exc)
        else:
            agent.password_hash = new_hash
            now = _now()
            await db.execute(
                update(SuperAgentSession)
                .where(SuperAgentSession.agent_id == agent.id, SuperAgentSession.revoked_at.is_(None))
                .values(revoked_at=now)
            )
            raw_token = secrets.token_urlsafe(32)
            db.add(SuperAgentSession(
                token_hash=hash_token(raw_token), csrf_token=secrets.token_urlsafe(32),
                agent_id=agent.id, created_at=now,
                expires_at=now + timedelta(seconds=SESSION_SECONDS),
            ))
            await db.commit()
            response = RedirectResponse(url="/agent", status_code=303)
            response.set_cookie(
                SESSION_COOKIE, raw_token, max_age=SESSION_SECONDS, path="/agent",
                secure=False, httponly=True, samesite="strict",
            )
            return response
    response = templates.TemplateResponse(
        request=request, name="agent_password.html",
        context={"agent": agent, "csrf_token": session.csrf_token, "error": error},
        status_code=422,
    )
    return _credential_response(response)
