#!/usr/bin/env python3
"""
sdk-ai/mcp-server/server.py — Official Login512 Model Context Protocol (MCP) Server
Implements the Model Context Protocol (JSON-RPC 2.0 over stdio) for Claude Desktop,
Cursor, Windsurf, VS Code, Cline, Roo Code, and autonomous coding agents.
Provides instant project inspection, full 28-framework SDK installation instructions,
and security auditing for Post-Quantum Biometrics & Zero-Image Passkeys.
"""

from __future__ import annotations
import json
import re
import os
from pathlib import Path
import sys
from typing import Any, Optional

SDK_CATALOG: dict[str, dict[str, Any]] = {
    # 1. Frontend Web (7)
    "react": {
        "name": "React",
        "category": "frontend",
        "install_command": "npm install https://login512.com/packages/react.tgz",
        "package_url": "https://login512.com/packages/react.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-react",
        "quick_code": """import { Login512Provider, Login512Button } from '@login512/react';

<Login512Provider publishableKey="l512_pk_live_your_key" endpoint="https://api.login512.com">
  <Login512Button
    onSuccess={async (token) => {
      // your backend verifies the token with the SECRET key (POST /v1/token/verify)
      await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }) });
    }}
  />
</Login512Provider>""",
    },
    "nextjs": {
        "name": "Next.js",
        "category": "frontend",
        "install_command": "npm install https://login512.com/packages/nextjs.tgz",
        "package_url": "https://login512.com/packages/nextjs.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-nextjs",
        "quick_code": """'use client';
import { Login512Button } from '@login512/nextjs/client';

export default function LoginPage() {
  return <Login512Button onSuccess={async (res) => { await fetch('/api/auth', { method: 'POST', body: JSON.stringify(res) }); }} />;
}""",
    },
    "vue": {
        "name": "Vue.js",
        "category": "frontend",
        "install_command": "npm install https://login512.com/packages/vue.tgz",
        "package_url": "https://login512.com/packages/vue.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-vue",
        "quick_code": """<template>
  <Login512Auth publishable-key="l512_pk_live_your_key" @success="onSuccess" />
</template>
<script setup>
import { Login512Auth } from '@login512/vue';
const onSuccess = (res) => console.log('Token:', res.token);
</script>""",
    },
    "nuxt": {
        "name": "Nuxt",
        "category": "frontend",
        "install_command": "npm install https://login512.com/packages/nuxt.tgz",
        "package_url": "https://login512.com/packages/nuxt.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-nuxt",
        "quick_code": """// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@login512/nuxt'],
  login512: { publishableKey: process.env.LOGIN512_PK }
});""",
    },
    "svelte": {
        "name": "Svelte / SvelteKit",
        "category": "frontend",
        "install_command": "npm install https://login512.com/packages/svelte.tgz",
        "package_url": "https://login512.com/packages/svelte.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-svelte",
        "quick_code": """<script lang="ts">
import { Login512Button } from '@login512/svelte';
</script>
<Login512Button publishableKey="l512_pk_live_your_key" on:success={(e) => console.log(e.detail.token)} />""",
    },
    "angular": {
        "name": "Angular",
        "category": "frontend",
        "install_command": "npm install https://login512.com/packages/angular.tgz",
        "package_url": "https://login512.com/packages/angular.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-angular",
        "quick_code": """import { Component } from '@angular/core';
import { Login512ButtonComponent } from '@login512/angular';

@Component({
  standalone: true,
  imports: [Login512ButtonComponent],
  template: `<login512-ng-button publishableKey="l512_pk_live_your_key" (success)="onAuthSuccess($event)"></login512-ng-button>`
})
export class LoginComponent {
  onAuthSuccess({ token }: { token: string }) { /* POST token to your backend, which verifies it */ }
}""",
    },
    "html5": {
        "name": "HTML5 Web Component",
        "category": "frontend",
        "install_command": '<script src="https://login512.com/sdk/login512-sdk.js"></script>',
        "package_url": "https://login512.com/sdk/login512-sdk.js",
        "guide_url": "https://login512.com/guide.html#sdk-web-component",
        "quick_code": """<script src="https://login512.com/sdk/login512-sdk.js"></script>
<login512-card client-id="l512_pk_live_your_key"></login512-card>
<script>
document.querySelector('login512-card').addEventListener('l512:success', (e) => {
  console.log('Biometric Token:', e.detail.token);
});
</script>""",
    },

    # 2. Backend APIs (14)
    "node_express": {
        "name": "Node.js Express",
        "category": "backend",
        "install_command": "npm install https://login512.com/packages/node-express.tgz",
        "package_url": "https://login512.com/packages/node-express.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-node-express",
        "quick_code": """const express = require('express');
const { login512Auth } = require('@login512/express');

const app = express();
app.use('/api/protected', login512Auth({ secretKey: process.env.LOGIN512_SECRET_KEY }));
app.get('/api/protected/user', (req, res) => res.json({ user: req.login512User }));""",
    },
    "node_nestjs": {
        "name": "Node.js NestJS",
        "category": "backend",
        "install_command": "npm install https://login512.com/packages/node-nestjs.tgz",
        "package_url": "https://login512.com/packages/node-nestjs.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-node-nestjs",
        "quick_code": """import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { Login512Guard } from '@login512/nestjs';

@Controller('user')
export class UserController {
  @Get('profile')
  @UseGuards(Login512Guard)   // reads LOGIN512_SECRET_KEY; verifies the Bearer token on this request
  getProfile(@Req() req) { return req.login512User; }
}""",
    },
    "node_fastify": {
        "name": "Node.js Fastify",
        "category": "backend",
        "install_command": "npm install https://login512.com/packages/node-fastify.tgz",
        "package_url": "https://login512.com/packages/node-fastify.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-node-fastify",
        "quick_code": """const fastify = require('fastify')();
const login512 = require('@login512/fastify');

fastify.register(login512, { secretKey: process.env.LOGIN512_SECRET_KEY });
fastify.get('/api/protected', { preHandler: [fastify.verifyLogin512] }, async (req, reply) => {
  return { user: req.login512User };
});""",
    },
    "fastapi": {
        "name": "Python FastAPI",
        "category": "backend",
        "install_command": "pip install https://login512.com/packages/fastapi.tar.gz",
        "package_url": "https://login512.com/packages/fastapi.tar.gz",
        "guide_url": "https://login512.com/guide.html#sdk-python-fastapi",
        "quick_code": """from fastapi import FastAPI, Depends
from login512_fastapi import Login512Bearer

app = FastAPI()
auth = Login512Bearer(secret_key=os.getenv('LOGIN512_SECRET_KEY'))

@app.get('/api/profile')
async def profile(claims: dict = Depends(auth)):   # 401 for invalid, replayed or forged tokens
    return {'user_id': claims['sub']}""",
    },
    "django": {
        "name": "Python Django",
        "category": "backend",
        "install_command": "pip install https://login512.com/packages/django.tar.gz",
        "package_url": "https://login512.com/packages/django.tar.gz",
        "guide_url": "https://login512.com/guide.html#sdk-python-django",
        "quick_code": """# settings.py
INSTALLED_APPS += ['login512_django']
AUTHENTICATION_BACKENDS = ['login512_django.backend.Login512AuthBackend', 'django.contrib.auth.backends.ModelBackend']
LOGIN512_SECRET_KEY = os.getenv('LOGIN512_SECRET_KEY')

# urls.py: POST /login512/login/ {"token": "..."} -> Django session; GET /login512/nonce/
urlpatterns += [path('login512/', include('login512_django.urls'))]""",
    },
    "flask": {
        "name": "Python Flask",
        "category": "backend",
        "install_command": "pip install https://login512.com/packages/flask.tar.gz",
        "package_url": "https://login512.com/packages/flask.tar.gz",
        "guide_url": "https://login512.com/guide.html#sdk-python-flask",
        "quick_code": """from flask import Flask, jsonify, g
from flask_login512 import Login512, login512_required

app = Flask(__name__)
app.config['LOGIN512_SECRET_KEY'] = os.getenv('LOGIN512_SECRET_KEY')
Login512(app)

@app.route('/api/profile')
@login512_required
def profile():
    return jsonify({'user_id': g.login512_user['sub']})""",
    },
    "laravel": {
        "name": "PHP & Laravel",
        "category": "backend",
        "install_command": "curl -s https://login512.com/sdk/php/Login512.php -o app/Services/Login512.php",
        "package_url": "https://login512.com/sdk/php/Login512.php",
        "guide_url": "https://login512.com/guide.html#sdk-php-laravel",
        "quick_code": """use Login512\\Laravel\\Facades\\Login512;   // composer path repo from login512-laravel.zip

public function authenticate(Request $request) {
    $result = Login512::verifyToken((string) $request->input('token'));
    if (!empty($result['session_allowed'])) {   // not just 'valid': a valid token may still need step-up
        $user = User::firstOrCreate(['login512_id' => $result['claims']['sub']]);
        Auth::login($user);
        return response()->json(['status' => 'success']);
    }
    return response()->json(['error' => 'Invalid biometric token'], 401);
}""",
    },
    "symfony": {
        "name": "PHP Symfony",
        "category": "backend",
        "install_command": "curl -sO https://login512.com/packages/symfony.zip && unzip symfony.zip -d packages/login512-symfony-bundle && composer config repositories.login512 path packages/login512-symfony-bundle && composer require 'login512/login512-symfony-bundle:*'",
        "package_url": "https://login512.com/packages/symfony.zip",
        "guide_url": "https://login512.com/guide.html#sdk-php-symfony",
        "quick_code": """# .env.local: LOGIN512_SECRET_KEY=l512_sk_...  LOGIN512_PUBLISHABLE_KEY=l512_pk_...
# config/routes/login512.yaml  (GET /login512/nonce, POST /login512/verify)
login512:
    resource: '@Login512SymfonyBundle/config/routes.php'

# config/packages/security.yaml
security:
    providers:
        login512: { id: Login512\\SymfonyBundle\\Security\\Login512UserProvider }
    firewalls:
        main:
            provider: login512
            custom_authenticators: [Login512\\SymfonyBundle\\Security\\Login512Authenticator]

# Login page: nonce = (await fetch('/login512/nonce')).json().nonce -> Login512 button ({ nonce, endpoint }) ->
# POST /login512/verify {"token"} (JSON) starts the Symfony session. In a controller: Login512Client::verifyToken()
# and check 'session_allowed'.""",
    },
    "spring_boot": {
        "name": "Java Spring Boot",
        "category": "backend",
        "install_command": "curl -s https://login512.com/packages/spring-boot.zip -o spring-boot.zip",
        "package_url": "https://login512.com/packages/spring-boot.zip",
        "guide_url": "https://login512.com/guide.html#sdk-java-spring-boot",
        "quick_code": """// application.yml  (login512-spring-boot-starter auto-configures a Login512Client bean)
login512:
  secret-key: ${LOGIN512_SECRET_KEY}
  endpoint: https://api.login512.com
// Login512VerifyResult r = login512Client.verify(token, nonceOrNull); if (r.sessionAllowed()) { r.subject() ... }""",
    },
    "quarkus": {
        "name": "Java Quarkus",
        "category": "backend",
        "install_command": "curl -s https://login512.com/packages/quarkus.zip -o quarkus.zip",
        "package_url": "https://login512.com/packages/quarkus.zip",
        "guide_url": "https://login512.com/guide.html#sdk-java-quarkus",
        "quick_code": """// Login512IdentityProvider verifies every token with the Login512 API
Login512IdentityProvider l512 = new Login512IdentityProvider(System.getenv("LOGIN512_SECRET_KEY"));
String userId = l512.verifiedUserId(token);   // null when invalid, replayed, forged or step-up required
if (userId == null) throw new NotAuthorizedException("Login512");""",
    },
    "go": {
        "name": "Go (Golang)",
        "category": "backend",
        "install_command": "curl -s https://login512.com/packages/go.zip -o login512-go.zip",
        "package_url": "https://login512.com/packages/go.zip",
        "guide_url": "https://login512.com/guide.html#sdk-go",
        "quick_code": """// 1. unzip login512-go.zip
// 2. in go.mod: replace github.com/login512/login512-go => ./login512-go

import "github.com/login512/login512-go"

client, err := login512.NewClient(os.Getenv("LOGIN512_SECRET_KEY"))
res, err := client.VerifyToken(ctx, token, "")
if err == nil && res.Valid {
    fmt.Printf("Verified User: %s\\n", res.Claims.Subject)
}""",
    },
    "rust": {
        "name": "Rust",
        "category": "backend",
        "install_command": "curl -s https://login512.com/packages/rust.zip -o login512-rs.zip",
        "package_url": "https://login512.com/packages/rust.zip",
        "guide_url": "https://login512.com/guide.html#sdk-rust",
        "quick_code": """// 1. unzip login512-rs.zip
// 2. in Cargo.toml: login512 = { path = "./login512-rs" }

let client = login512::Login512Client::new(secret_key)?;
let res = client.verify_token_with_nonce(&token, None).await?;   // Some(nonce) when your server issued one
if res.valid {
    println!("User: {:?}", res.user_id);   // else res.error: TOKEN_ALREADY_USED, TOKEN_BAD_SIGNATURE, ...
}""",
    },
    "dotnet": {
        "name": "C# & .NET Core",
        "category": "backend",
        "install_command": "curl -s https://login512.com/packages/dotnet.zip -o login512-dotnet.zip",
        "package_url": "https://login512.com/packages/dotnet.zip",
        "guide_url": "https://login512.com/guide.html#sdk-dotnet",
        "quick_code": """// 1. unzip login512-dotnet.zip
// 2. dotnet add reference ./login512-dotnet/Login512.AspNetCore.csproj

builder.Services.AddAuthentication("Login512")
    .AddScheme<Login512AuthenticationOptions, Login512AuthenticationHandler>("Login512", opt => {
        opt.SecretKey = builder.Configuration["LOGIN512_SECRET_KEY"];
    });""",
    },
    "ruby_rails": {
        "name": "Ruby on Rails",
        "category": "backend",
        "install_command": "curl -s https://login512.com/packages/ruby-rails.zip -o login512-rails.zip",
        "package_url": "https://login512.com/packages/ruby-rails.zip",
        "guide_url": "https://login512.com/guide.html#sdk-ruby-rails",
        "quick_code": """# 1. unzip login512-rails.zip
# 2. in Gemfile: gem 'login512', path: './login512-rails'

Login512.configure do |config|
  config.secret_key = ENV['LOGIN512_SECRET_KEY']
end""",
    },

    # 3. Mobile Apps (4)
    "flutter": {
        "name": "Flutter Mobile",
        "category": "mobile",
        "install_command": "curl -s https://login512.com/packages/flutter.zip -o login512_flutter.zip",
        "package_url": "https://login512.com/packages/flutter.zip",
        "guide_url": "https://login512.com/guide.html#sdk-flutter",
        "quick_code": """// pubspec.yaml: login512_flutter: { path: ./login512_flutter }   (from flutter.zip)
final r = await Login512LoginView.login(context,
    publishableKey: 'l512_pk_live_...', appOrigin: 'https://app.example.com', nonce: nonceFromYourServer);
if (r.token != null) { /* POST r.token to YOUR server, which verifies it with the secret key */ }""",
    },
    "react_native": {
        "name": "React Native & Expo",
        "category": "mobile",
        "install_command": "npm install https://login512.com/packages/react-native.tgz",
        "package_url": "https://login512.com/packages/react-native.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-react-native",
        "quick_code": """import { Login512Login } from '@login512/react-native';   // needs react-native-webview
<Login512Login publishableKey="l512_pk_live_..." appOrigin="https://app.example.com" nonce={nonce}
  onSuccess={({ token }) => sendToYourServer(token)} onError={({ code }) => console.warn(code)} />""",
    },
    "ios": {
        "name": "iOS Native (Swift)",
        "category": "mobile",
        "install_command": "curl -s https://login512.com/packages/ios.zip -o Login512Kit.zip",
        "package_url": "https://login512.com/packages/ios.zip",
        "guide_url": "https://login512.com/guide.html#sdk-ios",
        "quick_code": """import Login512   // Swift Package from ios.zip (iOS 15+), Info.plist NSCameraUsageDescription
var o = Login512LoginViewController.Options(publishableKey: "l512_pk_live_...")
o.appOrigin = "https://app.example.com"
present(Login512LoginViewController(options: o) { result in if case .success(let token) = result { sendToYourServer(token) } }, animated: true)""",
    },
    "android": {
        "name": "Android Native (Kotlin)",
        "category": "mobile",
        "install_command": "curl -s https://login512.com/packages/android.zip -o login512-android.zip",
        "package_url": "https://login512.com/packages/android.zip",
        "guide_url": "https://login512.com/guide.html#sdk-android",
        "quick_code": """// app/libs/login512-android-2.1.1.aar (from android.zip)
private val login512 = registerForActivityResult(Login512Contract()) { r -> r.token?.let { sendToYourServer(it) } }
login512.launch(Login512Contract.Input(publishableKey = "l512_pk_live_...", appOrigin = "https://app.example.com", nonce = nonce))""",
    },

    # 4. CMS & Plugins (3)
    "wordpress": {
        "name": "WordPress & WooCommerce",
        "category": "cms",
        "install_command": "wp plugin install https://login512.com/packages/wordpress.zip --activate",
        "package_url": "https://login512.com/packages/wordpress.zip",
        "guide_url": "https://login512.com/guide.html#sdk-wordpress",
        "quick_code": """# Or upload via WordPress Admin:
# 1. Plugins -> Add New -> Upload Plugin -> select wordpress.zip
# 2. Click Install Now and Activate
# 3. Enter Publishable Key & Secret Key in Settings -> Login512""",
    },
    "shopify": {
        "name": "Shopify App Extension",
        "category": "cms",
        "install_command": "curl -s https://login512.com/packages/shopify.zip -o login512-shopify.zip",
        "package_url": "https://login512.com/packages/shopify.zip",
        "guide_url": "https://login512.com/guide.html#sdk-shopify",
        "quick_code": """// 1. unzip login512-shopify.zip
// 2. Include in theme.liquid or hydrogen app:
// <script src="https://login512.com/sdk/login512-sdk.js"></script>""",
    },
    "drupal": {
        "name": "Drupal",
        "category": "cms",
        "install_command": "curl -LO https://login512.com/packages/drupal.zip && unzip drupal.zip -d web/modules/custom && drush en login512",
        "package_url": "https://login512.com/packages/drupal.zip",
        "guide_url": "https://login512.com/guide.html#sdk-drupal",
        "quick_code": """# Configuration > People > Login512 (/admin/config/people/login512): endpoint, publishable key, secret key
# The Login512 button appears on the user login form:
#   GET /login512/nonce -> nonce in the Drupal session
#   POST /login512/verify {"token"} -> verified with the SECRET key + expected_nonce -> Drupal session""",
    },
    "joomla": {
        "name": "Joomla",
        "category": "cms",
        "install_command": "Joomla > System > Install > Extensions > Install from URL: https://login512.com/packages/joomla.zip",
        "package_url": "https://login512.com/packages/joomla.zip",
        "guide_url": "https://login512.com/guide.html#sdk-joomla",
        "quick_code": """# System > Plugins > "System - Login512": enable, set endpoint, publishable key, secret key.
# The button appears on site and administrator login forms; the token is verified with the SECRET key
# (com_ajax task=verify) and the user signs in through Joomla's own onUserLogin.""",
    },
    "gateway": {
        "name": "Nginx / Kong Gateway",
        "category": "backend",
        "install_command": "curl -LO https://login512.com/packages/gateway.zip && unzip gateway.zip",
        "package_url": "https://login512.com/packages/gateway.zip",
        "guide_url": "https://login512.com/guide.html#sdk-gateway",
        "quick_code": """# python3 login512-gateway/nginx/login512_gateway.py  (LOGIN512_SECRET_KEY, LOGIN512_PUBLISHABLE_KEY, L512_GW_SESSION_SECRET)
location /protected/ {
    auth_request /_login512_auth;                       # see login512-auth.conf
    auth_request_set $login512_user $upstream_http_x_login512_user;
    error_page 401 = @login512_login;
    proxy_set_header X-Login512-User $login512_user;    # percent-encoded user id
    proxy_pass http://backend_upstream;
}""",
    },
    "capacitor": {
        "name": "Ionic / Capacitor",
        "category": "mobile",
        "install_command": "npm install https://login512.com/packages/capacitor.tgz",
        "package_url": "https://login512.com/packages/capacitor.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-capacitor",
        "quick_code": """import { login512Login } from '@login512/capacitor';
// capacitor.config.ts: server: { iosScheme: 'https' }; tenant allowed origin: https://localhost
const { token } = await login512Login({ publishableKey: 'l512_pk_live_...', endpoint: 'https://api.login512.com' });
// send the token to YOUR server, which verifies it with the secret key""",
    },
    "strapi": {
        "name": "Strapi Headless CMS",
        "category": "cms",
        "install_command": "npm install https://login512.com/packages/strapi.tgz",
        "package_url": "https://login512.com/packages/strapi.tgz",
        "guide_url": "https://login512.com/guide.html#sdk-strapi",
        "quick_code": """// config/plugins.js  (Strapi 5; add next to the existing entries)
module.exports = ({ env }) => ({
  login512: { enabled: true, config: { secretKey: env('LOGIN512_SECRET_KEY') } },
});

// Frontend: nonce first (httpOnly cookie on the Strapi host), then exchange the token for a users-permissions session
const { nonce } = await (await fetch(STRAPI + '/api/login512/nonce', { credentials: 'include' })).json();
// ... Login512 button with { nonce } gives `token` ...
const r = await fetch(STRAPI + '/api/login512/login', { method: 'POST', credentials: 'include',
  headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }) });
const { jwt, user } = await r.json(); // 401 when the token is invalid, replayed, forged or the nonce does not match""",
    },
}

TOOLS = [
    {
        "name": "login512_inspect_project",
        "description": "Inspects project directory to detect programming language, framework (React, Next.js, Vue, Nuxt, Svelte, Angular, Express, NestJS, Fastify, FastAPI, Django, Flask, Laravel, Symfony, Spring Boot, Quarkus, Go, Rust, .NET Core, Ruby on Rails, Flutter, iOS, Android, WordPress, Shopify, Strapi) and recommend official integration package.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "project_path": {
                    "type": "string",
                    "description": "Absolute or relative path to project root (defaults to current directory)",
                }
            },
        },
    },
    {
        "name": "login512_get_instructions",
        "description": "Returns exact, verified installation commands, package download URLs (HTTP 200 live), copy-paste-ready code snippets, and deep guide anchor links for any of the 28 official Login512 SDKs and plugins.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "framework": {
                    "type": "string",
                    "description": "Target framework or language (e.g., 'react', 'nextjs', 'fastapi', 'django', 'flask', 'go', 'dotnet', 'laravel', 'spring_boot', 'flutter', 'wordpress', etc.)",
                }
            },
            "required": ["framework"],
        },
    },
    {
        "name": "login512_list_sdks",
        "description": "Lists all 28 official Login512 SDKs and plugins across Frontend Web, Backend APIs, Mobile Apps, and CMS plugins with their official package URLs.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "category": {
                    "type": "string",
                    "description": "Optional category filter: 'all', 'frontend', 'backend', 'mobile', 'cms'",
                }
            },
        },
    },
    {
        "name": "login512_audit_code",
        "description": "Audits client or server integration code to ensure compliance with Zero-Image privacy, post-quantum verification, and replay protection.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "code": {
                    "type": "string",
                    "description": "Source code snippet to audit",
                },
                "filename": {
                    "type": "string",
                    "description": "Filename being audited (e.g. 'auth.ts', 'login.php')",
                }
            },
            "required": ["code"],
        },
    },
    {
        "name": "login512_setup_2fa_and_genesis",
        "description": "Generates drop-in code to replace legacy TOTP / Google Authenticator with Login512 Biometric 2FA (Face + Fingerprint/Passkey), adds the 'Use Login512 instead of legacy Password/LINE/Google next time' one-click upgrade toggle, and configures First-Time Genesis Mode for initial passwordless Superadmin registration.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "framework": {
                    "type": "string",
                    "description": "Target framework or language (e.g., 'react', 'nextjs', 'html5', 'fastapi', 'laravel', 'node_express')",
                },
                "mode": {
                    "type": "string",
                    "description": "Integration mode: '2fa_upgrade', 'genesis_first_boot', or 'both' (default: 'both')",
                },
            },
        },
    },
    {
        "name": "login512_smart_checkin",
        "description": "Login512 Smart Check-in: an open-source check-in app (rotating signed QR + optional Wi-Fi IP lock + face/passkey) "
                       "with 5 industry presets in one codebase (classroom, workplace, event, checkpoint, dev-reference). Returns the "
                       "presets with download links, how to add a new industry (one JSON file), which files to copy to add Login512 to "
                       "another system (ERP, POS, LMS, HR, SaaS), the security rules that must not be broken, and server deployment notes.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "goal": {
                    "type": "string",
                    "description": "'overview' (default), 'add_preset' (new industry), 'integrate' (reuse the Login512 pattern in another system) or 'deploy' (run it on a server)",
                },
                "preset": {
                    "type": "string",
                    "description": "Optional preset id to focus on: classroom, workplace, event, checkpoint, dev-reference",
                },
            },
        },
    },
]

ALIASES: dict[str, str] = {
    "reactjs": "react",
    "next": "nextjs",
    "vuejs": "vue",
    "sveltekit": "svelte",
    "express": "node_express",
    "expressjs": "node_express",
    "nestjs": "node_nestjs",
    "fastify": "node_fastify",
    "node": "node_express",
    "nodejs": "node_express",
    "python": "fastapi",
    "py": "fastapi",
    "php": "laravel",
    "golang": "go",
    "c#": "dotnet",
    "csharp": "dotnet",
    ".net": "dotnet",
    "aspnet": "dotnet",
    "rails": "ruby_rails",
    "ruby": "ruby_rails",
    "spring": "spring_boot",
    "springboot": "spring_boot",
    "swift": "ios",
    "swiftui": "ios",
    "kotlin": "android",
    "compose": "android",
    "wp": "wordpress",
    "woocommerce": "wordpress",
    "html": "html5",
    "cdn": "html5",
}

# Same detection as sdk-ai/cli/login512-agent.py (audit 2026-11-21): read the dependency files, list every match,
# never guess. The old version turned any package.json into node_express, any composer.json into laravel and any
# Python project into fastapi, and stopped at the first match (React + Express reported only Express).
_JS_DEPS = [("react-native", "react_native"), ("next", "nextjs"), ("nuxt", "nuxt"), ("@strapi/strapi", "strapi"),
            ("@angular/core", "angular"), ("@sveltejs/kit", "svelte"), ("svelte", "svelte"), ("vue", "vue"),
            ("react", "react"), ("@nestjs/core", "node_nestjs"), ("fastify", "node_fastify"), ("express", "node_express")]
_JS_FILE_FALLBACK = [("nextjs", ["next.config.js", "next.config.mjs", "next.config.ts"]),
                     ("nuxt", ["nuxt.config.js", "nuxt.config.ts"]), ("svelte", ["svelte.config.js"]),
                     ("angular", ["angular.json"]), ("vue", ["src/App.vue"]),
                     ("react", ["src/App.tsx", "src/App.jsx", "src/App.js"])]


def _read_text(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8", errors="ignore")
    except OSError:
        return ""


def _has_word(text: str, name: str) -> bool:
    return re.search(r"(?<![\w.-])" + re.escape(name) + r"(?![\w-])", text, re.I) is not None


def detect_stacks(base: Path) -> list[str]:
    detected: list[str] = []

    def add(stack: str) -> None:
        if stack not in detected:
            detected.append(stack)

    if (base / "package.json").exists():
        try:
            pkg = json.loads(_read_text(base / "package.json") or "{}")
            deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})}
            for dep, stack in _JS_DEPS:
                if dep in deps:
                    add(stack)
        except (ValueError, AttributeError):
            for stack, files in _JS_FILE_FALLBACK:
                if any((base / f).exists() for f in files):
                    add(stack)
    py_text = " ".join(_read_text(base / f) for f in
                       ("requirements.txt", "requirements-dev.txt", "pyproject.toml", "Pipfile", "setup.py", "setup.cfg"))
    if (base / "manage.py").exists():
        add("django")
    for dep in ("django", "fastapi", "flask"):
        if _has_word(py_text, dep):
            add(dep)
    if (base / "composer.json").exists():
        try:
            req = json.loads(_read_text(base / "composer.json") or "{}").get("require") or {}
            if "laravel/framework" in req:
                add("laravel")
            if "symfony/framework-bundle" in req:
                add("symfony")
        except (ValueError, AttributeError):
            pass
    if (base / "artisan").exists():
        add("laravel")
    if (base / "symfony.lock").exists():
        add("symfony")
    if (base / "wp-config.php").exists() or (base / "wp-content").is_dir():
        add("wordpress")
    gradle = " ".join(_read_text(base / f) for f in ("build.gradle", "build.gradle.kts", "app/build.gradle",
                                                     "app/build.gradle.kts", "pom.xml"))
    if (base / "pubspec.yaml").exists() and "flutter" in _read_text(base / "pubspec.yaml"):
        add("flutter")
    if "com.android" in gradle:
        add("android")
    if (base / "Package.swift").exists() or any(base.glob("*.xcodeproj")) or any(base.glob("*.xcworkspace")):
        add("ios")
    if (base / "go.mod").exists():
        add("go")
    if (base / "Cargo.toml").exists():
        add("rust")
    if any(base.glob("*.csproj")) or any(base.glob("*.sln")):
        add("dotnet")
    if "quarkus" in gradle:
        add("quarkus")
    elif "spring-boot" in gradle or "org.springframework.boot" in gradle:
        add("spring_boot")
    if _has_word(_read_text(base / "Gemfile"), "rails"):
        add("ruby_rails")
    return detected


def inspect_project(project_path: Optional[str] = None) -> dict[str, Any]:
    base = Path(project_path or ".").resolve()
    detected = detect_stacks(base)

    primary = detected[0] if detected else "html5"
    matched_sdk = SDK_CATALOG.get(primary, SDK_CATALOG["html5"])

    return {
        "project_root": str(base),
        "detected_frameworks": detected if detected else ["html5 (Universal Web)"],
        "recommended_sdk": matched_sdk["name"],
        "install_command": matched_sdk["install_command"],
        "package_url": matched_sdk["package_url"],
        "guide_url": matched_sdk["guide_url"],
        "quick_code": matched_sdk["quick_code"],
        "auto_installer_command": f"curl -sSL https://login512.com/login512-agent.py | python3 - install --stack {primary}",
    }


# Audit 2026-11-20 (see docs/audit/AUDIT-PLAN-2026-11-20.md). Only what was verified end-to-end is "verified".
SDK_AUDIT_STATUS: dict[str, str] = {
    'dotnet': 'verified 2026-11-21 in Docker against a real backend (valid / replay / forged / wrong and right nonce) (.NET 8 SDK)',
    'rust': 'verified 2026-11-21 in Docker against a real backend (valid / replay / forged / wrong and right nonce) (rust stable); HTTPS works (2.1.0 had no TLS backend)',
    'ruby_rails': 'verified 2026-11-21 in Docker against a real backend (valid / replay / forged / wrong and right nonce) (ruby:3.3)',
    'drupal': 'verified 2026-11-21 inside a real Drupal 11 (Docker): browser login plus 10 checks (replay, forged, login CSRF, nonce, no takeover, Thai names)',
    'joomla': 'verified 2026-11-21 inside a real Joomla 5 (Docker), installed from joomla.zip: browser login plus 10 checks',
    'gateway': 'verified 2026-11-21 behind real nginx 1.30.7 and real Kong 3.9: 9 checks plus the browser flow (session cookie, forged header overwritten, open redirect blocked)',
    'capacitor': 'verified 2026-11-21 in a browser (real button and frame, token verified by the server); not yet run on an iOS/Android device',
    'html5': 'verified: browser SDK used by login512.com itself (face + passkey + 2FA flows)',
    'react': 'verified 2026-11-21: installed from the .tgz, renders the real Login512 button, opens the real auth frame, returns a token the server verifies, and reports an error (never a token) when the SDK cannot load',
    'vue': 'verified 2026-11-21: installed from the .tgz, renders the real Login512 button, opens the real auth frame, returns a token the server verifies, and reports an error (never a token) when the SDK cannot load',
    'svelte': 'verified 2026-11-21: installed from the .tgz, renders the real Login512 button, opens the real auth frame, returns a token the server verifies, and reports an error (never a token) when the SDK cannot load (Svelte 4 and 5)',
    'angular': 'verified 2026-11-21: installed from the .tgz, renders the real Login512 button, opens the real auth frame, returns a token the server verifies, and reports an error (never a token) when the SDK cannot load (built with Angular 17, tested in an Angular 19 AOT app)',
    'nuxt': 'verified 2026-11-21: installed from the .tgz, renders the real Login512 button, opens the real auth frame, returns a token the server verifies, and reports an error (never a token) when the SDK cannot load (Nuxt 3 SSR build)',
    'nextjs': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'node_express': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'node_nestjs': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'node_fastify': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'fastapi': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'flask': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'django': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported); login view, nonce view and Django session tested in a real Django project',
    'laravel': 'verified 2026-11-21 inside a real Laravel 12 app installed from the zip with composer (Facade, login512.verified middleware, Blade directives)',
    'wordpress': 'verified 2026-11-21 inside a real WordPress 6.7 (Docker): browser login on wp-login.php plus 10 checks (replay, forged, login CSRF, nonce, no takeover of existing users, Thai names); plugin 2.1.2',
    'strapi': 'verified 2026-11-21 inside a real Strapi 5.63 app (Docker, SQLite), installed from strapi.tgz 2.1.2: browser login from a separate frontend origin plus 28 checks (users-permissions JWT and refresh cookie, replay, forged, nonce / login CSRF, step-up, no takeover of existing usernames or emails, new users get the authenticated role, blocked users, legacy JWT mode); Strapi 4 not tested',
    'symfony': 'verified 2026-11-21 inside a real Symfony 7.4 app (Docker, PHP 8.5), installed from symfony.zip 2.1.1 with composer: browser login plus 24 checks (session, replay, forged, nonce / login CSRF, step-up, subject admin is not the app admin, user_mapper, Login512Client in a controller); Symfony 6.4 not tested',
    'go': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'quarkus': 'verified 2026-11-21 against a real backend (valid / replayed / forged tokens; nonce where supported)',
    'spring_boot': "verified 2026-11-21 in Docker against a real backend (valid / replay / forged / wrong and right nonce); a real Spring Boot 3.3 app with the starter's auto-configured Login512Client (2.1.0 did not compile)",
    'react_native': 'verified 2026-11-21: bridge page tested in a browser (real SDK, token verified by the server) and the component with react-test-renderer; not yet run on a device',
    'ios': 'verified 2026-11-21: Login512Core unit tests pass (Swift on Linux) and the bridge page is tested in a browser; the WKWebView view controller needs Xcode on a Mac: not yet compiled for iOS; not yet run on a device',
    'android': 'verified 2026-11-21: builds against Android SDK 34 (release AAR), bridge unit tests pass, bridge page tested in a browser; not yet run on a device',
    'flutter': 'verified 2026-11-21: flutter analyze and tests pass, bridge page tested in a browser; not yet run on a device',
    'shopify': 'NOT FUNCTIONAL: the package only contains a banner, no login integration.',
}
AUDIT_NOTE = ("Packages without a 'verified' audit_status are not verified yet (audit 2026-11-21). Always verify tokens on your "
              "server with POST /v1/token/verify and your SECRET key; never trust a client-side success callback.")


def _status(key: str) -> str:
    return SDK_AUDIT_STATUS.get(key, "unverified: audit pending")


def get_instructions(framework: str) -> dict[str, Any]:
    raw = framework.lower().strip().replace(" ", "_").replace("-", "_")
    key = ALIASES.get(raw, raw)
    data = SDK_CATALOG.get(key)
    if not data:
        # Search by substring
        for k, v in SDK_CATALOG.items():
            if raw in k or raw in v["name"].lower():
                data = v
                key = k
                break

    if not data:
        return {
            "error": f"Framework '{framework}' not found.",
            "available_frameworks": list(SDK_CATALOG.keys()),
            "catalog_url": "https://login512.com/sdks.html",
            "guide_url": "https://login512.com/guide.html",
        }

    return {
        "framework": data["name"],
        "category": data["category"],
        "install_command": data["install_command"],
        "package_download_url": data["package_url"],
        "guide_anchor_url": data["guide_url"],
        "universal_agent_installer": f"curl -sSL https://login512.com/login512-agent.py | python3 - install --stack {key}",
        "code_example": data["quick_code"],
        "audit_status": _status(key),
        "note": AUDIT_NOTE,
    }


def list_sdks(category: Optional[str] = None) -> dict[str, Any]:
    cat = (category or "all").lower().strip()
    result = []
    for key, item in SDK_CATALOG.items():
        if cat == "all" or item["category"] == cat:
            result.append({
                "key": key,
                "name": item["name"],
                "category": item["category"],
                "install_command": item["install_command"],
                "package_url": item["package_url"],
                "guide_url": item["guide_url"],
                "audit_status": _status(key),
            })
    return {
        "total": len(result),
        "category_filter": cat,
        "sdks": result,
        "note": AUDIT_NOTE,
    }


def audit_code(code: str, filename: Optional[str] = None) -> dict[str, Any]:
    findings: list[str] = []
    score = 100

    # 1. Check for secret key leak in frontend
    if "l512_sk_" in code and any(ext in (filename or "") for ext in (".js", ".ts", ".jsx", ".tsx", ".vue", ".svelte", ".html")):
        findings.append("CRITICAL: Secret key ('l512_sk_...') detected in client-side code! Secret keys must reside strictly on the server backend.")
        score -= 50

    # 2. Check for zero-image violation
    forbidden_terms = ["save_image", "write_image", "cv2.imwrite", "localStorage.setItem('frame", "fs.writeFileSync"]
    for term in forbidden_terms:
        if term in code:
            findings.append(f"WARNING: Potential zero-image policy violation with term '{term}'. Facial frames must not be saved to disk/storage.")
            score -= 30

    # 3. Patterns that were account-takeover holes before the 2026-11-20 API change
    lower = code.lower()
    is_client = any(ext in (filename or "") for ext in (".js", ".ts", ".jsx", ".tsx", ".vue", ".svelte", ".html")) or "<script" in lower
    if is_client and "/v1/2fa/" in code:
        findings.append("CRITICAL: /v1/2fa/* is called from client-side code. These endpoints require the SECRET key and must be "
                        "called by your backend for the logged-in user (the API rejects publishable keys since 2026-11-20).")
        score -= 40
    if "shouldbypasslegacylogin" in lower and ("location.href" in lower or "redirect" in lower):
        findings.append("CRITICAL: shouldBypassLegacyLogin() is a localStorage UI hint that anyone can set. Never skip "
                        "authentication because of it; verify a Login512 token on your server.")
        score -= 40
    if "enrollpasskey(" in lower and "enrollmenttoken" not in lower and "enrollment_token" not in lower:
        findings.append("HIGH: enrollPasskey() without an enrollment token. Passkey registration needs a token minted by your "
                        "backend (POST /v1/enrollment-tokens, secret key) for the logged-in user.")
        score -= 25
    if is_client and ("onsuccess" in lower or "login512:success" in lower) and "token/verify" not in lower and "fetch(" not in lower:
        findings.append("HIGH: success callback with no server round-trip. Send the token to your backend and verify it with "
                        "POST /v1/token/verify (secret key) before creating a session.")
        score -= 20
    if "l512-genesis-first-boot" in lower:
        findings.append("CRITICAL: the old default genesis key was removed. Set LOGIN512_GENESIS_KEY (>= 24 random chars) on the server.")
        score -= 30

    score = max(0, score)
    return {
        "audit_passed": score >= 80,
        "score": score,
        "findings": findings if findings else ["Code adheres to Login512 Zero-Image Privacy & NIST FIPS 204 Post-Quantum standards."],
    }


def setup_2fa_and_genesis(framework: str = "html5", mode: str = "both") -> dict[str, Any]:
    """Generates drop-in code for Login512 2FA (TOTP replacement + Primary Upgrade) & First-Time Genesis Mode."""
    fw = (framework or "html5").strip().lower()
    m = (mode or "both").strip().lower()
    result: dict[str, Any] = {
        "framework": fw,
        "mode": m,
        "guide_url": "https://login512.com/guide.html#ch3-2fa-totp",
    }

    if m in ("2fa_upgrade", "both"):
        result["totp_replacement_2fa"] = {
            "summary": "Replace 6-digit TOTP with a face / passkey scan. The browser only scans; your BACKEND mints the "
                       "enrollment token and verifies the result with the SECRET key for the user who is logged in.",
            "security": [
                "/v1/2fa/* require the SECRET key (server-to-server). Publishable keys are rejected since 2026-11-20.",
                "Use external_user_id from YOUR session, never a value sent by the browser.",
                "shouldBypassLegacyLogin() is only a UI hint (localStorage). Never skip authentication because of it.",
            ],
            "api_endpoints": [
                "POST https://login512.com/v1/2fa/enroll-token      (secret key, backend)",
                "POST https://login512.com/v1/2fa/verify            (secret key, backend)",
                "POST https://login512.com/v1/2fa/upgrade-primary   (secret key, backend)",
                "GET  https://login512.com/v1/2fa/status/{external_user_id} (secret key, backend)",
            ],
            "frontend_snippet": """<script src="https://login512.com/sdk/login512-sdk.js"></script>
<link rel="stylesheet" href="https://login512.com/sdk/login512-sdk.css">
<div id="login512-2fa-slot"></div>
<script>
const sdk = Login512.init({ publishableKey: 'l512_pk_live_your_key' });
sdk.mount2FA('#login512-2fa-slot', {
  externalUserId: currentLoggedInUser.id,
  getEnrollmentToken: () => fetch('/api/2fa/enroll-token', { method: 'POST' }).then(r => r.json()),
  verifyOnServer: (token, ctx) => fetch('/api/2fa/verify', {
    method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token, upgradeToPrimary: ctx.upgradeToPrimary })
  }).then(r => r.json()),
  onSuccess: (res) => { if (res.verified === true) window.location.href = '/dashboard'; }
});
</script>""",
            "backend_snippet_node_express": """// Your backend: the user is already logged in with password/LINE/Google (req.session.userId)
const L512 = 'https://login512.com';
const SK = process.env.LOGIN512_SECRET_KEY;            // l512_sk_... never sent to the browser
app.post('/api/2fa/enroll-token', requireSession, async (req, res) => {
  const r = await fetch(`${L512}/v1/2fa/enroll-token`, { method: 'POST',
    headers: { 'Authorization': `Bearer ${SK}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ external_user_id: req.session.userId }) });
  res.status(r.status).json(await r.json());
});
app.post('/api/2fa/verify', requireSession, async (req, res) => {
  const r = await fetch(`${L512}/v1/2fa/verify`, { method: 'POST',
    headers: { 'Authorization': `Bearer ${SK}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ external_user_id: req.session.userId, biometric_token: req.body.token,
                           upgrade_to_primary: !!req.body.upgradeToPrimary }) });
  const data = await r.json();
  if (r.ok && data.verified === true) req.session.secondFactor = true;   // only now is 2FA satisfied
  res.status(r.status).json(data);
});""",
        }

    if m in ("genesis_first_boot", "both"):
        result["first_time_genesis_mode"] = {
            "summary": "Zero-password first Superadmin: a one-time Genesis key from your server environment + a face or "
                       "passkey scan claims the first admin and permanently seals Genesis mode.",
            "security": [
                "There is NO default key. Set LOGIN512_GENESIS_KEY (>= 24 random characters) on the Login512 server; "
                "without it /v1/genesis/* return 403 (genesis disabled).",
                "The old published default 'L512-GENESIS-FIRST-BOOT' was removed on 2026-11-20.",
            ],
            "api_endpoints": [
                "GET  https://login512.com/v1/genesis/status        (returns enabled / sealed)",
                "POST https://login512.com/v1/genesis/enroll-token",
                "POST https://login512.com/v1/genesis/claim",
            ],
            "frontend_snippet": """<div id="genesis-setup"></div>
<script>
const sdk = Login512.init({ publishableKey: 'l512_pk_live_your_key' });
fetch('https://login512.com/v1/genesis/status', { headers: { 'Authorization': 'Bearer l512_pk_live_your_key' } })
  .then(r => r.json()).then(st => {
    if (st.enabled && st.genesis_required) {
      // The operator types the one-time LOGIN512_GENESIS_KEY into the form rendered here
      sdk.mountGenesisSetup('#genesis-setup', { onSuccess: () => window.location.href = '/admin' });
    }
  });
</script>""",
        }

    return result


SMART_CHECKIN_REPO = "https://github.com/login512/smart-checkin"
SMART_CHECKIN_RAW = "https://raw.githubusercontent.com/login512/smart-checkin/main"

# Kept equal to examples/smart-checkin/presets/*.json by backend/tests/test_mcp_server.py
SMART_CHECKIN_PRESETS = [
    {"id": "classroom", "icon": "🎓", "for": "Classes, tutoring, exam rooms",
     "notable": "Student ID + section, projector QR, stops buddy check-in and QR photos sent to group chats",
     "qr_rotate_sec": 7, "clock_out": False},
    {"id": "workplace", "icon": "🏢", "for": "Offices, shops, clinics, factories",
     "notable": "Clock-in / clock-out, optional office Wi-Fi IP lock, payroll CSV for Excel",
     "qr_rotate_sec": 7, "clock_out": True},
    {"id": "event", "icon": "🎟️", "for": "Events, workshops, fitness, VIP lounges",
     "notable": "Live attendee counter on the kiosk, no guest photos stored",
     "qr_rotate_sec": 7, "clock_out": False},
    {"id": "checkpoint", "icon": "🛡️", "for": "Security patrols, housekeeping rounds, service desks",
     "notable": "Faster 6 s QR, station rounds with notes",
     "qr_rotate_sec": 6, "clock_out": False},
    {"id": "dev-reference", "icon": "💻", "for": "Developers adding Login512 to ERP / POS / SaaS",
     "notable": "Opens the Token Verify Inspector (expected_nonce, mod, act, jti, ML-DSA-65)",
     "qr_rotate_sec": 7, "clock_out": True},
]

SMART_CHECKIN_RULES = [
    "Never expose LOGIN512_SECRET_KEY (l512_sk_...) to browser code, public files or /api/config.",
    "Every login and check-in is verified on the server with POST /v1/token/verify; reject unless valid === true, "
    "session_allowed === true and step_up_required !== true.",
    "Face logins are bound to a server-issued single-use expected_nonce; passkey logins must have claims.mod === 'PASSKEY'.",
    "Never store face photos or frames (database, disk or logs).",
    "Presence is the rotating signed QR (5-8 s) plus the optional Wi-Fi IP allowlist, never browser GPS.",
    "DEMO_MOCK_AUTH=false in production (the app refuses mock mode under NODE_ENV=production or a non-localhost URL).",
    "Keep CSRF protection (x-csrf-token) on state-changing admin routes.",
    "A second install on the same Login512 account logs the existing Superadmin in (nonce-bound, same id only) instead of enrolling again.",
]


def smart_checkin(goal: Optional[str] = None, preset: Optional[str] = None) -> dict[str, Any]:
    g = (goal or "overview").lower().strip()
    presets = [dict(p, zip_url=f"{SMART_CHECKIN_REPO}/releases/latest/download/login512-smart-checkin-{p['id']}.zip",
                    file=f"presets/{p['id']}.json") for p in SMART_CHECKIN_PRESETS]
    if preset:
        wanted = preset.lower().strip()
        presets = [p for p in presets if p["id"] == wanted] or presets
    result: dict[str, Any] = {
        "summary": "Open-source check-in app and reference integration for Login512. One codebase, 5 industry presets; "
                   "a new industry is one JSON file. Node.js 22.5+, Express, SQLite, plain HTML/JS, Docker.",
        "repo": SMART_CHECKIN_REPO,
        "latest_release": f"{SMART_CHECKIN_REPO}/releases/latest",
        "agent_guide": f"{SMART_CHECKIN_RAW}/AGENTS.md",
        "presets": presets,
        "quickstart": [
            "Download a preset ZIP (or git clone the repo)",
            "cp .env.example .env   # add l512_pk_... and l512_sk_... from https://login512.com/portal/index.html",
            "npm install && npm start   # http://localhost:3512 ; the one-time setup key is printed in the terminal",
            "Add the site's address (e.g. http://localhost:3512) to Allowed Origins in the Login512 Portal",
        ],
        "rules_that_must_not_be_broken": SMART_CHECKIN_RULES,
    }
    if g in ("add_preset", "overview"):
        result["add_preset"] = {
            "guide": f"{SMART_CHECKIN_RAW}/docs/ADD_A_PRESET.md",
            "steps": [
                "Copy the closest preset: cp presets/event.json presets/<new-id>.json",
                "Set id = file name (2-32 chars a-z 0-9 -), icon, accent (#RRGGBB), supportsClockOut, allowNote, "
                "showDevInspectorDefault, defaultQrRotateSec (whole number 5-8)",
                "Rewrite every th and en text: name, shortName, tagline, defaultOrgName, defaultSiteName, memberLabel, "
                "memberCodeLabel, memberCodePlaceholder, groupLabel, groupPlaceholder, siteLabel, actionInLabel, "
                "actionOutLabel, notePlaceholder, kioskHeadline, kioskSub, csvHeaders",
                "npm run check:presets && npm test",
                "It appears after the 5 built-ins in /setup and /admin; npm run build:zips makes its ZIP too",
            ],
            "no_code_change_needed": True,
        }
    if g in ("integrate", "overview"):
        result["integrate"] = {
            "copy_these": {
                "src/login512/client.js": "server-side Login512 client: enrollment tokens, /v1/token/verify, nonce and passkey checks",
                "src/login512/qr-guard.js": "rotating HMAC-signed QR (5-8 s) and Wi-Fi IP allowlist (exact IP + IPv4 CIDR)",
                "src/login512/genesis.js": "first Superadmin with a one-time setup key, then locked forever",
            },
            "raw_files": [f"{SMART_CHECKIN_RAW}/src/login512/{f}" for f in ("client.js", "qr-guard.js", "genesis.js")],
            "browser_sdk": "https://login512.com/sdk/login512-sdk.js (face, passkey and phone QR all run in the Login512 frame)",
        }
    if g in ("deploy", "overview"):
        result["deploy"] = {
            "env": {
                "HOST": "127.0.0.1 behind Nginx / Cloudflare (otherwise the port is reachable directly)",
                "TRUST_PROXY": "1 behind a proxy, so the Wi-Fi IP allowlist sees the visitor's real IP",
                "PUBLIC_BASE_URL": "https://your-domain",
                "DEMO_MOCK_AUTH": "false",
            },
            "allowed_origins": "Add https://your-domain to Allowed Origins in the Login512 Portal (Settings)",
            "docker": "docker compose up -d (reads .env)",
        }
    return result


SUPPORTED_PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")


def _call_tool(name: str, arguments: dict[str, Any]) -> dict[str, Any]:
    if name == "login512_inspect_project":
        return inspect_project(arguments.get("project_path"))
    if name == "login512_get_instructions":
        return get_instructions(arguments.get("framework", "vanilla"))
    if name == "login512_list_sdks":
        return list_sdks(arguments.get("category", "all"))
    if name == "login512_audit_code":
        return audit_code(arguments.get("code", ""), arguments.get("filename"))
    if name == "login512_setup_2fa_and_genesis":
        return setup_2fa_and_genesis(arguments.get("framework", "html5"), arguments.get("mode", "both"))
    if name == "login512_smart_checkin":
        return smart_checkin(arguments.get("goal"), arguments.get("preset"))
    raise KeyError(name)


def handle(req: Any) -> Optional[dict[str, Any]]:
    """One JSON-RPC message -> one response, or None for notifications (MCP: notifications get no reply)."""
    if not isinstance(req, dict) or req.get("jsonrpc") != "2.0" or "method" not in req:
        return {"jsonrpc": "2.0", "id": req.get("id") if isinstance(req, dict) else None,
                "error": {"code": -32600, "message": "Invalid Request"}}
    method = req["method"]
    is_notification = "id" not in req
    req_id = req.get("id")
    params = req.get("params") or {}

    if is_notification:  # e.g. notifications/initialized, notifications/cancelled
        return None
    if method == "initialize":
        asked = params.get("protocolVersion")
        version = asked if asked in SUPPORTED_PROTOCOL_VERSIONS else SUPPORTED_PROTOCOL_VERSIONS[0]
        return {"jsonrpc": "2.0", "id": req_id, "result": {
            "protocolVersion": version,
            "capabilities": {"tools": {"listChanged": False}},
            "serverInfo": {"name": "login512-mcp", "version": "2.3.0"},
        }}
    if method == "ping":
        return {"jsonrpc": "2.0", "id": req_id, "result": {}}
    if method == "tools/list":
        return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
    if method == "tools/call":
        name = params.get("name")
        try:
            output = _call_tool(name, params.get("arguments") or {})
        except KeyError:
            return {"jsonrpc": "2.0", "id": req_id, "result": {
                "content": [{"type": "text", "text": f"Unknown tool: {name}"}], "isError": True}}
        except Exception as e:  # tool bug: report as a tool error, keep the server alive
            return {"jsonrpc": "2.0", "id": req_id, "result": {
                "content": [{"type": "text", "text": f"Tool error: {type(e).__name__}: {e}"}], "isError": True}}
        return {"jsonrpc": "2.0", "id": req_id, "result": {
            "content": [{"type": "text", "text": json.dumps(output, indent=2, ensure_ascii=False)}]}}
    return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}}


def main():
    # MCP stdio is UTF-8. On Windows the default console encoding (e.g. cp874 / cp1252) cannot write emoji or some
    # scripts, and json.dumps(..., ensure_ascii=False) then crashed the server with UnicodeEncodeError.
    for stream in (sys.stdin, sys.stdout):
        try:
            stream.reconfigure(encoding="utf-8")
        except (AttributeError, ValueError):
            pass
    for line in sys.stdin:
        line_str = line.strip()
        if not line_str:
            continue
        try:
            req = json.loads(line_str)
        except json.JSONDecodeError:
            res: Optional[dict[str, Any]] = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
        else:
            if isinstance(req, list):  # JSON-RPC batch
                out = [r for r in (handle(x) for x in req) if r is not None]
                res = out or None  # type: ignore[assignment]
            else:
                res = handle(req)
        if res is not None:
            sys.stdout.write(json.dumps(res, ensure_ascii=False) + "\n")
            sys.stdout.flush()


if __name__ == "__main__":
    main()
