//go:build ignore

package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	"strings"
)

// Module definitions: line number ranges and their descriptions
type Module struct {
	Start   int // inclusive 1-indexed
	End     int // inclusive 1-indexed
	Title   string
	Comment string
}

var modules = []Module{
	{1, 26, "包声明与依赖导入", "程序入口包声明及标准库、项目内部包、第三方库导入"},
	{27, 48, "核心数据结构 UI", "UI 结构体，聚合所有服务依赖，是 Web 层的核心中枢"},
	{49, 170, "页面数据模型 PageData", "统一的页面渲染数据载体，包含设备、任务、告警、配置等所有页面所需数据"},
	{171, 222, "辅助视图类型", "DeviceOverviewRow、TaskDeviceRow、ConfigStatusView 等轻量视图模型"},
	{223, 545, "构造函数与模板函数注册", "NewUI 创建 UI 实例，注册模板渲染所需的 FuncMap（JSON序列化、类型标签、规则映射等）"},
	{546, 625, "依赖注入方法", "SetStateRepo、SetAuditRepo、SetAlarmCollector 等延迟注入方法"},
	{626, 762, "路由注册 Routes", "将 HTTP 路径映射到对应的页面处理函数和 API 动作函数"},
	{763, 825, "模板渲染与设备工具方法", "render 模板渲染、findDevice 设备查找、ensureDevicesLoaded 缓存加载"},
	{826, 895, "仪表盘页面", "pageDashboard 渲染系统总览：设备统计、告警概览、异常设备、最近任务"},
	{896, 1244, "管控台页面", "pageConsole 设备能力矩阵展示、actionConsoleSave 保存管控配置"},
	{1245, 1410, "设备列表与批量操作", "pageDevices 列表、actionDeviceAdd 添加、actionDiscoverySearch 发现、actionDevicesBatchAction 批量操作"},
	{1410, 1726, "设备详情与单设备控制", "pageDevice 详情、pageDeviceControl 控制、actionDeviceAction 下发动作、actionDeviceConfigApply 配置应用"},
	{1727, 1833, "任务管理模块", "pageTasks 列表、taskPageData 数据、actionCreateTask 创建任务、pageTask 详情"},
	{1834, 1913, "模型管理", "pageModels 模型概览、actionModelSync 同步模型到设备"},
	{1914, 2004, "告警与诊断", "pageDiagnostics 诊断页、pageAlarms 告警中心（分页过滤）"},
	{2005, 2066, "资源管理", "pageResources 资源概览、actionResourceSync 资源同步"},
	{2067, 2133, "配置资产管理——模板", "pageAssetTemplates 列表、CRUD 操作"},
	{2134, 2475, "配置资产管理——模板操作", "actionAssetTemplateCreate 创建、Clone 克隆、Rename 重命名、Delete 删除、GraphSave 可视化保存、Export 导出"},
	{2476, 2748, "场景配置与视频通道", "pagePlan/pageAssetProfiles 场景管理、pageRecognitionUnits 视频通道、CRUD"},
	{2749, 2856, "通道部署与设备分配", "pageDeviceAssignments 部署矩阵、actionDeviceAssignmentSave/Delete 分配操作"},
	{2857, 3038, "视频源与第三方服务", "pageAssetVideoSources 视频源管理、pageAssetIntegrations 集成服务管理、CRUD"},
	{3039, 3209, "调试参数管理", "pageAssetOverlays 调试参数列表、actionAssetOverlaySave/Clone/Delete"},
	{3210, 3600, "配置预览与格式转换", "assetPageData 跨页共享数据、profileEditor 场景编辑器、configPreview 配置预览渲染"},
	{3601, 4414, "设备配置交互 UI", "pageDeviceConfigUI/Friendly 友好配置页面、configPreviewPageData 预览、actionDeviceConfigUIPlan/Apply 应用下发"},
	{4415, 4476, "人脸库上传与设备代理", "actionDeviceFaceGalleryUpload 上传人脸图片、actionDeviceFaceGalleryReload 重新加载人脸库"},
	{4477, 4652, "视频监控与人脸库管理", "pageMonitor 监控页、proxyHLS 代理推流、actionFaceGalleryAdd/Build 人脸库构建"},
	{4653, 4822, "人脸库页面与设备指标 API", "pageFaceGallery 人脸库展示、serveFacePhoto 照片服务、apiDeviceMetrics 指标接口"},
	{4823, 4863, "控制台视图模型", "DeviceMetric、ConsoleDeviceData、ConsoleChannel、ConsoleFeature 等控制台用数据结构"},
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintln(os.Stderr, "Usage: go run extract_src.go <source.go>")
		os.Exit(1)
	}
	srcPath := os.Args[1]

	f, err := os.Open(srcPath)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer f.Close()

	var lines []string
	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}

	outPath := "docs/source_code.md"
	out, err := os.Create(outPath)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer out.Close()

	w := bufio.NewWriter(out)

	// Header
	w.WriteString("# 工业安全生产视觉监测平台——核心源代码\n\n")
	w.WriteString("**软件名称**：工业安全生产视觉监测平台\n")
	w.WriteString("**版本**：V1.0\n")
	w.WriteString("**开发语言**：Go\n")
	w.WriteString("**源文件**：`internal/web/ui.go`\n")
	w.WriteString("**总行数**：" + fmt.Sprintf("%d", len(lines)) + "\n\n")
	w.WriteString("---\n\n")
	w.WriteString("## 模块概览\n\n")
	for _, m := range modules {
		w.WriteString(fmt.Sprintf("- **%s**（第 %d-%d 行）：%s\n", m.Title, m.Start, m.End, m.Comment))
	}
	w.WriteString("\n---\n\n")

	// Find function/type boundaries for better formatting
	typeBoundaryRe := regexp.MustCompile(`^(func |type )`)
	commentRe := regexp.MustCompile(`^//`) // Sometimes we use // comments

	moduleIdx := 0
	for i, line := range lines {
		lineNum := i + 1

		// Check if we need to start a new module section
		for moduleIdx < len(modules) && lineNum == modules[moduleIdx].Start {
			m := modules[moduleIdx]
			w.WriteString(fmt.Sprintf("## 模块 %d：%s\n", moduleIdx+1, m.Title))
			w.WriteString(fmt.Sprintf("> %s\n\n", m.Comment))
			w.WriteString("```go\n")
			moduleIdx++
		}

		// Check if we need to close a module section
		if moduleIdx > 0 && lineNum == modules[moduleIdx-1].End+1 {
			w.WriteString("```\n\n")
		}

		// Mark important type/function boundaries (but these are already covered by modules)
		_ = typeBoundaryRe
		_ = commentRe

		w.WriteString(line + "\n")
	}

	// Close last module if needed
	if moduleIdx > 0 && moduleIdx <= len(modules) {
		w.WriteString("```\n\n")
	}

	w.Flush()
	fmt.Printf("Done: %s (%d lines)\n", outPath, len(lines))
}
