"""First-use SSH host-key pin for the explicitly authorized OLT ID 1."""
import asyncio
import base64
import hashlib
from pathlib import Path
import socket

import paramiko
from sqlalchemy import select

from app.core.database import AsyncSessionLocal
from app.models.models import OLTDevice

KEY_NAME = "OLT_1_SSH_HOST_KEY_SHA256"


def upsert_env(path: Path, key: str, value: str) -> None:
    lines = path.read_text(encoding="utf-8").splitlines() if path.exists() else []
    prefix = key + "="
    lines = [line for line in lines if not line.startswith(prefix)]
    lines.append(prefix + value)
    path.write_text("\n".join(lines) + "\n", encoding="utf-8")


async def main():
    async with AsyncSessionLocal() as db:
        olt = await db.get(OLTDevice, 1)
        if not olt or (olt.vendor, olt.model) != ("C-DATA", "FD1601S-B1"):
            raise RuntimeError("Authorized C-DATA FD1601S-B1 target is unavailable")
        host, port = olt.host, olt.api_port
    sock = socket.create_connection((host, port), timeout=8)
    transport = paramiko.Transport(sock)
    try:
        transport.start_client(timeout=8)
        key = transport.get_remote_server_key()
        fingerprint = base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode("ascii").rstrip("=")
    finally:
        transport.close()
    upsert_env(Path(".env"), KEY_NAME, "SHA256:" + fingerprint)
    print("pinned=authorized_olt_1")


asyncio.run(main())
