// 独立运行：go run scripts/inspect_db.go
// 查看 MongoDB 数据结构（需先建立 SSH 隧道）

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	uri := "mongodb://localhost:27017"
	client, err := mongo.Connect(options.Client().ApplyURI(uri))
	if err != nil {
		log.Fatalf("连接失败: %v", err)
	}
	defer client.Disconnect(context.TODO())

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 验证连接
	var result bson.M
	if err = client.Database("admin").RunCommand(ctx, bson.D{{Key: "ping", Value: 1}}).Decode(&result); err != nil {
		log.Fatalf("Ping 失败: %v", err)
	}
	fmt.Println("MongoDB 连接成功\n")

	// 列出数据库（排除系统库）
	dbs, err := client.ListDatabaseNames(ctx, bson.M{
		"name": bson.M{"$nin": []string{"admin", "config", "local"}},
	})
	if err != nil {
		log.Fatalf("列出数据库失败: %v", err)
	}

	output := map[string]interface{}{"databases": []interface{}{}}

	for _, dbName := range dbs {
		db := client.Database(dbName)
		colls, _ := db.ListCollectionNames(ctx, bson.M{})

		dbInfo := map[string]interface{}{
			"name":        dbName,
			"collections": []interface{}{},
		}

		for _, collName := range colls {
			coll := db.Collection(collName)
			count, _ := coll.CountDocuments(ctx, bson.M{})

			var sample bson.M
			_ = coll.FindOne(ctx, bson.M{}).Decode(&sample)

			dbInfo["collections"] = append(dbInfo["collections"].([]interface{}), map[string]interface{}{
				"name":   collName,
				"count": count,
				"sample": sample,
			})
		}

		output["databases"] = append(output["databases"].([]interface{}), dbInfo)
	}

	jsonBytes, _ := json.MarshalIndent(output, "", "  ")
	fmt.Println(string(jsonBytes))
}
