电脑wifi路由器软件代码(AI生成)

C#源码

<Window x:Class="WiFiShared.Main"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WiFiShared - WiFi 路由器"
        Height="700"
        Width="960"
        MinHeight="620"
        MinWidth="860"
        WindowStartupLocation="CenterScreen"
        Icon="pack://application:,,,/Assets/app.ico"
        Background="#EEF2F7"
        FontFamily="Segoe UI"
        FontSize="13">
    <Window.Resources>
        <SolidColorBrush x:Key="CardBrush" Color="White"/>
        <SolidColorBrush x:Key="BorderBrush" Color="#E2E8F0"/>
        <SolidColorBrush x:Key="TextPrimaryBrush" Color="#1E293B"/>
        <SolidColorBrush x:Key="TextSecondaryBrush" Color="#64748B"/>
        <SolidColorBrush x:Key="AccentBrush" Color="#2563EB"/>

        <Style TargetType="TextBox">
            <Setter Property="Padding" Value="10,8"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Background" Value="White"/>
        </Style>

        <Style TargetType="PasswordBox">
            <Setter Property="Padding" Value="10,8,44,8"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Background" Value="White"/>
        </Style>

        <Style x:Key="PasswordRevealButtonStyle" TargetType="Button">
            <Setter Property="Width" Value="34"/>
            <Setter Property="Height" Value="30"/>
            <Setter Property="Padding" Value="0"/>
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Foreground" Value="#64748B"/>
            <Setter Property="FontSize" Value="12"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="ToolTip" Value="显示密码"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border x:Name="Root" Background="{TemplateBinding Background}" CornerRadius="6" Padding="{TemplateBinding Padding}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="Root" Property="Background" Value="#F1F5F9"/>
                                <Setter Property="Foreground" Value="#334155"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style TargetType="ComboBox">
            <Setter Property="Padding" Value="8,6"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="Background" Value="White"/>
        </Style>

        <Style x:Key="CardBorderStyle" TargetType="Border">
            <Setter Property="Background" Value="{StaticResource CardBrush}"/>
            <Setter Property="CornerRadius" Value="12"/>
            <Setter Property="Padding" Value="20"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="BorderThickness" Value="1"/>
        </Style>

        <Style x:Key="SectionTitleStyle" TargetType="TextBlock">
            <Setter Property="FontSize" Value="16"/>
            <Setter Property="FontWeight" Value="SemiBold"/>
            <Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}"/>
        </Style>

        <Style x:Key="FieldLabelStyle" TargetType="TextBlock">
            <Setter Property="Foreground" Value="#475569"/>
            <Setter Property="Margin" Value="0,0,0,6"/>
        </Style>

        <Style x:Key="PrimaryButtonStyle" TargetType="Button">
            <Setter Property="Background" Value="{StaticResource AccentBrush}"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="BorderThickness" Value="0"/>
            <Setter Property="Padding" Value="16,9"/>
            <Setter Property="MinWidth" Value="120"/>
            <Setter Property="Cursor" Value="Hand"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Background="{TemplateBinding Background}" CornerRadius="8" Padding="{TemplateBinding Padding}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Background" Value="#CBD5E1"/>
                    <Setter Property="Foreground" Value="#94A3B8"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <Style x:Key="SecondaryButtonStyle" TargetType="Button" BasedOn="{StaticResource PrimaryButtonStyle}">
            <Setter Property="Background" Value="White"/>
            <Setter Property="Foreground" Value="#334155"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="8" Padding="{TemplateBinding Padding}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Background" Value="#F8FAFC"/>
                    <Setter Property="Foreground" Value="#CBD5E1"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <Style x:Key="ListViewStyle" TargetType="ListView">
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="Background" Value="#F8FAFC"/>
            <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
            <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        </Style>

        <Style TargetType="GridViewColumnHeader">
            <Setter Property="Background" Value="#F1F5F9"/>
            <Setter Property="Foreground" Value="#475569"/>
            <Setter Property="FontWeight" Value="SemiBold"/>
            <Setter Property="Padding" Value="10,8"/>
            <Setter Property="BorderBrush" Value="{StaticResource BorderBrush}"/>
            <Setter Property="BorderThickness" Value="0,0,1,1"/>
        </Style>
    </Window.Resources>

    <Grid Margin="24">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Margin="0,0,0,20">
            <TextBlock Text="WiFiShared" FontSize="30" FontWeight="SemiBold" Foreground="{StaticResource TextPrimaryBrush}"/>
            <TextBlock Text="通过 USB WiFi 网卡将有线网络共享为 WiFi 热点" Margin="0,6,0,0" FontSize="14" Foreground="{StaticResource TextSecondaryBrush}"/>
        </StackPanel>

        <Border Grid.Row="1" Style="{StaticResource CardBorderStyle}" Margin="0,0,0,16">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="16"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <TextBlock Grid.Row="0" Grid.Column="0" Text="热点名称 (SSID)" Style="{StaticResource FieldLabelStyle}"/>
                <TextBox x:Name="SsidTextBox" Grid.Row="1" Grid.Column="0" Margin="0,0,0,14"/>

                <TextBlock Grid.Row="0" Grid.Column="2" Text="WiFi 密码 (至少 8 位)" Style="{StaticResource FieldLabelStyle}"/>
                <Grid Grid.Row="1" Grid.Column="2" Margin="0,0,0,14">
                    <PasswordBox x:Name="PasswordBox"/>
                    <TextBox x:Name="PasswordTextBox" Padding="10,8,44,8" Visibility="Collapsed"/>
                    <Button x:Name="TogglePasswordVisibilityButton" Style="{StaticResource PasswordRevealButtonStyle}" Content="显示" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,6,0" Click="TogglePasswordVisibilityButton_Click"/>
                </Grid>

                <TextBlock Grid.Row="2" Grid.Column="0" Text="上行网络(共享来源)" Style="{StaticResource FieldLabelStyle}"/>
                <ComboBox x:Name="UpstreamComboBox" Grid.Row="3" Grid.Column="0" DisplayMemberPath="DisplayName"/>

                <TextBlock Grid.Row="2" Grid.Column="2" Text="USB WiFi 网卡" Style="{StaticResource FieldLabelStyle}"/>
                <TextBox x:Name="WiFiAdapterTextBox" Grid.Row="3" Grid.Column="2" IsReadOnly="True" Background="#F8FAFC"/>
            </Grid>
        </Border>

        <Grid Grid.Row="2">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1.1*"/>
                <ColumnDefinition Width="16"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Border Grid.Column="0" Style="{StaticResource CardBorderStyle}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <TextBlock Grid.Row="0" Text="运行状态" Style="{StaticResource SectionTitleStyle}"/>
                    <TextBlock x:Name="StatusTextBlock" Grid.Row="1" Margin="0,10,0,4" FontSize="15" Foreground="{StaticResource TextPrimaryBrush}"/>
                    <TextBlock x:Name="SupportTextBlock" Grid.Row="2" Margin="0,0,0,4" Foreground="{StaticResource TextSecondaryBrush}" TextWrapping="Wrap"/>
                    <TextBlock x:Name="ClientsTextBlock" Grid.Row="3" Margin="0,0,0,8" Foreground="{StaticResource TextSecondaryBrush}"/>

                    <DockPanel Grid.Row="4">
                        <TextBlock DockPanel.Dock="Top" Text="右键设备可拉黑、限速或编辑备注" Margin="0,0,0,6" FontSize="12" Foreground="#94A3B8"/>
                        <ListView x:Name="ClientsListView" Style="{StaticResource ListViewStyle}" MinHeight="180" MouseDoubleClick="ClientsListView_MouseDoubleClick" PreviewMouseRightButtonDown="ClientsListView_PreviewMouseRightButtonDown">
                            <ListView.View>
                                <GridView>
                                    <GridViewColumn Header="MAC 地址" Width="145">
                                        <GridViewColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding MacAddress}" FontFamily="Consolas" FontSize="12" Padding="8,6"/>
                                            </DataTemplate>
                                        </GridViewColumn.CellTemplate>
                                    </GridViewColumn>
                                    <GridViewColumn Header="备注" Width="90">
                                        <GridViewColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding DisplayRemark}" Padding="8,6" TextTrimming="CharacterEllipsis"/>
                                            </DataTemplate>
                                        </GridViewColumn.CellTemplate>
                                    </GridViewColumn>
                                    <GridViewColumn Header="下载" Width="88">
                                        <GridViewColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding DownloadRateText}" FontFamily="Consolas" FontSize="12" Padding="8,6" Foreground="#059669"/>
                                            </DataTemplate>
                                        </GridViewColumn.CellTemplate>
                                    </GridViewColumn>
                                    <GridViewColumn Header="上传" Width="88">
                                        <GridViewColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding UploadRateText}" FontFamily="Consolas" FontSize="12" Padding="8,6" Foreground="#D97706"/>
                                            </DataTemplate>
                                        </GridViewColumn.CellTemplate>
                                    </GridViewColumn>
                                    <GridViewColumn Header="累计流量" Width="96">
                                        <GridViewColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding SessionBytesText}" FontFamily="Consolas" FontSize="12" Padding="8,6" Foreground="#2563EB"/>
                                            </DataTemplate>
                                        </GridViewColumn.CellTemplate>
                                    </GridViewColumn>
                                    <GridViewColumn Header="策略" Width="96">
                                        <GridViewColumn.CellTemplate>
                                            <DataTemplate>
                                                <TextBlock Text="{Binding PolicyStatusText}" FontSize="12" Padding="8,6" FontWeight="SemiBold">
                                                    <TextBlock.Style>
                                                        <Style TargetType="TextBlock">
                                                            <Setter Property="Foreground" Value="#64748B"/>
                                                            <Style.Triggers>
                                                                <DataTrigger Binding="{Binding IsBlocked}" Value="True">
                                                                    <Setter Property="Foreground" Value="#DC2626"/>
                                                                </DataTrigger>
                                                                <MultiDataTrigger>
                                                                    <MultiDataTrigger.Conditions>
                                                                        <Condition Binding="{Binding IsBlocked}" Value="False"/>
                                                                        <Condition Binding="{Binding HasBandwidthLimit}" Value="True"/>
                                                                    </MultiDataTrigger.Conditions>
                                                                    <Setter Property="Foreground" Value="#7C3AED"/>
                                                                </MultiDataTrigger>
                                                            </Style.Triggers>
                                                        </Style>
                                                    </TextBlock.Style>
                                                </TextBlock>
                                            </DataTemplate>
                                        </GridViewColumn.CellTemplate>
                                    </GridViewColumn>
                                </GridView>
                            </ListView.View>
                            <ListView.ContextMenu>
                                <ContextMenu Opened="ClientsContextMenu_Opened">
                                    <MenuItem Header="编辑备注" Click="EditClientRemarkMenuItem_Click"/>
                                    <Separator/>
                                    <MenuItem x:Name="BlockClientMenuItem" Header="拉黑设备" Click="BlockClientMenuItem_Click"/>
                                    <MenuItem Header="设置限速..." Click="SetClientBandwidthMenuItem_Click"/>
                                    <MenuItem x:Name="ClearClientBandwidthMenuItem" Header="取消限速" Click="ClearClientBandwidthMenuItem_Click"/>
                                </ContextMenu>
                            </ListView.ContextMenu>
                        </ListView>
                    </DockPanel>
                </Grid>
            </Border>

            <Border Grid.Column="2" Style="{StaticResource CardBorderStyle}">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>
                    <Grid Grid.Row="0" Margin="0,0,0,12">
                        <TextBlock Text="网络适配器" Style="{StaticResource SectionTitleStyle}" VerticalAlignment="Center"/>
                        <Button Content="刷新" Style="{StaticResource SecondaryButtonStyle}" HorizontalAlignment="Right" MinWidth="72" Padding="12,6" Click="RefreshButton_Click"/>
                    </Grid>
                    <ListView x:Name="AdaptersListView" Grid.Row="1" Style="{StaticResource ListViewStyle}" MinHeight="220">
                        <ListView.View>
                            <GridView>
                                <GridViewColumn Header="名称" Width="72">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock Text="{Binding Name}" Padding="8,6"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Header="描述" Width="220">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock Text="{Binding Description}" Padding="8,6" TextWrapping="Wrap"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Header="状态" Width="72">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock Text="{Binding Status}" Padding="8,6"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                                <GridViewColumn Header="互联网" Width="64">
                                    <GridViewColumn.CellTemplate>
                                        <DataTemplate>
                                            <TextBlock Text="{Binding HasInternet}" Padding="8,6"/>
                                        </DataTemplate>
                                    </GridViewColumn.CellTemplate>
                                </GridViewColumn>
                            </GridView>
                        </ListView.View>
                    </ListView>
                </Grid>
            </Border>
        </Grid>

        <Border Grid.Row="3" Margin="0,16,0,0" Padding="16,14" Background="White" CornerRadius="12" BorderBrush="{StaticResource BorderBrush}" BorderThickness="1">
            <Grid>
                <TextBlock x:Name="MessageTextBlock" VerticalAlignment="Center" Foreground="#B45309" TextWrapping="Wrap" Margin="0,0,16,0"/>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                    <Button x:Name="StopButton" Content="停止共享" Style="{StaticResource SecondaryButtonStyle}" Margin="0,0,12,0" IsEnabled="False" Click="StopButton_Click"/>
                    <Button x:Name="StartButton" Content="启动 WiFi 路由器" Style="{StaticResource PrimaryButtonStyle}" MinWidth="150" Click="StartButton_Click"/>
                </StackPanel>
            </Grid>
        </Border>
    </Grid>
</Window>
main.xaml
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Windows.Networking.Connectivity;
using Windows.Networking.NetworkOperators;
using WinDivertSharp;
using Forms = System.Windows.Forms;

namespace WiFiShared;

// Models section - merged into main.xaml.cs

/// <summary>客户端策略:拉黑与带宽限速。</summary>
public sealed class ClientPolicy
{
    public bool Blocked { get; set; }
    public long? MaxBytesPerSecond { get; set; }
}

/// <summary>已连接客户端信息,含流量统计与策略状态。</summary>
public sealed class ConnectedClient
{
    public string MacAddress { get; init; } = string.Empty;
    public string? Remark { get; init; }
    public double? DownloadRateBytesPerSec { get; init; }
    public double? UploadRateBytesPerSec { get; init; }
    public long? SessionBytes { get; init; }
    public bool IsBlocked { get; init; }
    public long? MaxBytesPerSecond { get; init; }

    public string DisplayRemark => string.IsNullOrWhiteSpace(Remark) ? "\u2014" : Remark;
    public bool HasBandwidthLimit => MaxBytesPerSecond is > 0;

    public string PolicyStatusText
    {
        get
        {
            if (IsBlocked)
                return "已拉黑";
            if (MaxBytesPerSecond is { } limit && limit > 0)
                return $"限速 {NetworkTrafficFormatter.FormatRate(limit)}";
            return "\u2014";
        }
    }

    public string DownloadRateText => DownloadRateBytesPerSec is { } rate
        ? NetworkTrafficFormatter.FormatRate(rate)
        : "\u2014";

    public string UploadRateText => UploadRateBytesPerSec is { } rate
        ? NetworkTrafficFormatter.FormatRate(rate)
        : "\u2014";

    public string SessionBytesText => SessionBytes is { } total && total > 0
        ? NetworkTrafficFormatter.FormatSize(total)
        : "\u2014";

    public string DisplayText
    {
        get
        {
            var label = string.IsNullOrWhiteSpace(Remark) ? MacAddress : $"{MacAddress}  {Remark}";
            var traffic = NetworkTrafficFormatter.FormatTrafficSummary(
                DownloadRateBytesPerSec, UploadRateBytesPerSec, SessionBytes);
            return string.IsNullOrEmpty(traffic) ? label : $"{label}  {traffic}";
        }
    }
}

/// <summary>热点启动参数(SSID、密码、最大客户端数)。</summary>
public sealed class HotspotConfig
{
    public string Ssid { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
    public int MaxClients { get; set; } = 100;
}

/// <summary>热点运行状态与已连接设备列表。</summary>
public sealed class HotspotStatus
{
    public bool IsRunning { get; init; }
    public bool IsConfigured { get; init; }
    public string Ssid { get; init; } = string.Empty;
    public int ConnectedClients { get; init; }
    public int MaxClients { get; init; }
    public IReadOnlyList<ConnectedClient> Clients { get; init; } = Array.Empty<ConnectedClient>();
}

/// <summary>网络适配器摘要信息。</summary>
public sealed class NetworkAdapterInfo
{
    public string Name { get; init; } = string.Empty;
    public string DisplayName { get; init; } = string.Empty;
    public string Description { get; init; } = string.Empty;
    public string Status { get; init; } = string.Empty;
    public string HasInternet { get; init; } = string.Empty;
    public bool IsVirtual { get; init; }
    public bool IsWiFi { get; init; }
}

/// <summary>网络流量与速率的格式化工具。</summary>
internal static class NetworkTrafficFormatter
{
    public static string FormatRate(double bytesPerSecond)
    {
        if (bytesPerSecond < 1024)
            return $"{bytesPerSecond:0} B/s";
        if (bytesPerSecond < 1024 * 1024)
            return $"{bytesPerSecond / 1024d:0.##} KB/s";
        return $"{bytesPerSecond / (1024d * 1024d):0.##} MB/s";
    }

    public static string FormatSize(long bytes)
    {
        if (bytes < 1024)
            return $"{bytes} B";
        if (bytes < 1024 * 1024)
            return $"{bytes / 1024d:0.##} KB";
        if (bytes < 1024L * 1024 * 1024)
            return $"{bytes / (1024d * 1024d):0.##} MB";
        return $"{bytes / (1024d * 1024d * 1024d):0.##} GB";
    }

    public static string FormatTrafficSummary(
        double? downloadRate,
        double? uploadRate,
        long? sessionBytes)
    {
        var parts = new List<string>();
        if (downloadRate is { } down && down > 0)
            parts.Add($"↓{FormatRate(down)}");
        if (uploadRate is { } up && up > 0)
            parts.Add($"↑{FormatRate(up)}");
        if (sessionBytes is { } total && total > 0)
            parts.Add(FormatSize(total));
        return string.Join(" ", parts);
    }
}

/// <summary>内嵌 PowerShell / VBS 脚本(运行时写入临时目录执行)。</summary>
internal static class EmbeddedScripts
{
    public const string EnableInternetSharing = """
$ErrorActionPreference = 'Stop'
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedAccess'
$DisabledIndex = [uint32]4294967295
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$GatewayIp = '192.168.137.1'
$NetworkPrefix = 24

function Assert-HostedNetworkStarted {
    $status = cmd /c "chcp 65001>nul & netsh wlan show hostednetwork"
    if ($status -notmatch '(?i)Status\s*:\s*Started' -and $status -notmatch '状态\s*:\s*已启动') {
        throw 'Hosted network is not started. Run: netsh wlan start hostednetwork'
    }
}

function Get-UpstreamAdapter {
    Get-NetAdapter |
        Where-Object { $_.Status -eq 'Up' } |
        Where-Object { $_.InterfaceDescription -notmatch 'Hosted|Virtual|Wi-Fi Direct|Loopback|Miniport' } |
        ForEach-Object {
            $config = Get-NetIPConfiguration -InterfaceAlias $_.Name -ErrorAction SilentlyContinue
            [PSCustomObject]@{
                Adapter = $_
                Gateway = $config.IPv4DefaultGateway.NextHop
            }
        } |
        Where-Object { $_.Gateway -and $_.Gateway -ne '0.0.0.0' } |
        Select-Object -First 1 -ExpandProperty Adapter
}

function Get-HostedAdapter {
    Get-NetAdapter |
        Where-Object {
            $_.InterfaceDescription -match 'Microsoft Hosted Network Virtual Adapter' -and $_.Status -eq 'Up'
        } |
        Select-Object -First 1
}

function Stop-SharedAccessService {
    sc.exe stop SharedAccess 2>$null | Out-Null
    $deadline = (Get-Date).AddSeconds(8)
    while ((Get-Service SharedAccess -ErrorAction SilentlyContinue).Status -ne 'Stopped' -and (Get-Date) -lt $deadline) {
        Start-Sleep -Milliseconds 300
    }
}

function Start-SharedAccessService {
    sc.exe start SharedAccess 2>$null | Out-Null
    Start-Sleep -Seconds 2
    $service = Get-Service -Name SharedAccess -ErrorAction Stop
    if ($service.Status -ne 'Running') {
        Start-Service -Name SharedAccess -ErrorAction Stop
    }
}

function Clear-PrivateIPv4 {
    param([int]$IfIndex)

    Get-NetIPAddress -InterfaceIndex $IfIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Remove-NetIPAddress -Confirm:$false -ErrorAction SilentlyContinue
}

function Ensure-PrivateGatewayAddress {
    param(
        [int]$IfIndex,
        [string]$InterfaceAlias
    )

    $target = Get-NetIPAddress -InterfaceIndex $IfIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Where-Object { $_.IPAddress -eq $GatewayIp } |
        Select-Object -First 1

    if ($null -ne $target) {
        Write-Output "Private gateway already set: $GatewayIp on $InterfaceAlias"
        return
    }

    Clear-PrivateIPv4 -IfIndex $IfIndex
    Start-Sleep -Seconds 1
    New-NetIPAddress -InterfaceIndex $IfIndex -IPAddress $GatewayIp -PrefixLength $NetworkPrefix -ErrorAction Stop | Out-Null
    Write-Output "Assigned private gateway: $GatewayIp on $InterfaceAlias"
}

function Enable-IpForwarding {
    param(
        [string]$PublicAlias,
        [string]$PrivateAlias
    )

    Set-NetIPInterface -InterfaceAlias $PublicAlias -AddressFamily IPv4 -Forwarding Enabled -ErrorAction SilentlyContinue
    Set-NetIPInterface -InterfaceAlias $PrivateAlias -AddressFamily IPv4 -Forwarding Enabled -ErrorAction SilentlyContinue
}

function Enable-DhcpFirewallRules {
    netsh advfirewall firewall set rule name="Network Discovery (LLMNR-UDP-In)" new enable=yes 2>$null | Out-Null
    netsh advfirewall firewall add rule name="WiFiShared DHCP In" dir=in action=allow protocol=UDP localport=67 profile=private 2>$null | Out-Null
    netsh advfirewall firewall add rule name="WiFiShared DHCP Out" dir=out action=allow protocol=UDP localport=67 profile=private 2>$null | Out-Null
}

function Test-DhcpServerListening {
    return $null -ne (Get-NetUDPEndpoint -LocalPort 67 -ErrorAction SilentlyContinue | Select-Object -First 1)
}

function Enable-IcsRegistry {
    param(
        [uint32]$PublicIfIndex,
        [uint32]$PrivateIfIndex
    )

    Set-ItemProperty -Path $RegPath -Name PublicIndex -Value $PublicIfIndex -Type DWord
    Set-ItemProperty -Path $RegPath -Name PrivateIndex -Value $PrivateIfIndex -Type DWord
    Start-SharedAccessService

    $current = Get-ItemProperty -Path $RegPath
    if ([uint32]$current.PublicIndex -ne $PublicIfIndex -or [uint32]$current.PrivateIndex -ne $PrivateIfIndex) {
        throw "ICS registry verification failed. PublicIndex=$($current.PublicIndex) PrivateIndex=$($current.PrivateIndex)"
    }
}

function Enable-IcsCom {
    param(
        [string]$PublicConnectionName,
        [string]$PrivateConnectionName
    )

    $vbsPath = Join-Path $ScriptDir 'EnableInternetSharing.vbs'
    if (-not (Test-Path $vbsPath)) {
        throw "Missing COM helper: $vbsPath"
    }

    $arguments = @(
        '//NoLogo',
        $vbsPath,
        $PublicConnectionName,
        $PrivateConnectionName
    )

    $process = Start-Process -FilePath 'cscript.exe' -ArgumentList $arguments -Wait -PassThru -NoNewWindow
    if ($process.ExitCode -ne 0) {
        throw "ICS COM helper failed with exit code $($process.ExitCode)"
    }
}

Assert-HostedNetworkStarted

$publicAdapter = Get-UpstreamAdapter
$privateAdapter = Get-HostedAdapter

if ($null -eq $publicAdapter) {
    throw 'Upstream adapter with internet gateway not found.'
}

if ($null -eq $privateAdapter) {
    throw 'Hosted network virtual adapter not found. Start the hotspot first.'
}

Write-Output "Public adapter: $($publicAdapter.Name) ($($publicAdapter.ifIndex))"
Write-Output "Private adapter: $($privateAdapter.Name) ($($privateAdapter.ifIndex))"

Stop-SharedAccessService
Clear-PrivateIPv4 -IfIndex $privateAdapter.ifIndex
Enable-IpForwarding -PublicAlias $publicAdapter.Name -PrivateAlias $privateAdapter.Name
Enable-DhcpFirewallRules

$comOk = $false
try {
    Enable-IcsCom -PublicConnectionName $publicAdapter.Name -PrivateConnectionName $privateAdapter.Name
    $comOk = $true
    Write-Output 'ICS COM enabled.'
}
catch {
    Write-Output "ICS COM failed: $($_.Exception.Message)"
}

if (-not $comOk) {
    Ensure-PrivateGatewayAddress -IfIndex $privateAdapter.ifIndex -InterfaceAlias $privateAdapter.Name
    Enable-IcsRegistry -PublicIfIndex ([uint32]$publicAdapter.ifIndex) -PrivateIfIndex ([uint32]$privateAdapter.ifIndex)
    Write-Output 'ICS registry enabled.'
}
else {
    Start-Sleep -Seconds 2
    $gateway = Get-NetIPAddress -InterfaceIndex $privateAdapter.ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue |
        Where-Object { $_.IPAddress -eq $GatewayIp } |
        Select-Object -First 1
    if ($null -eq $gateway) {
        Ensure-PrivateGatewayAddress -IfIndex $privateAdapter.ifIndex -InterfaceAlias $privateAdapter.Name
    }
}

Stop-SharedAccessService
Start-SharedAccessService

if (-not (Test-DhcpServerListening)) {
    Write-Output 'Warning: DHCP server port 67 is not listening yet.'
}
else {
    Write-Output 'DHCP server is listening on port 67.'
}

$verify = Get-ItemProperty -Path $RegPath
Write-Output "Gateway=$GatewayIp Final PublicIndex=$($verify.PublicIndex) PrivateIndex=$($verify.PrivateIndex)"
Write-Output 'On the phone: forget WiFiShared, then reconnect to obtain 192.168.137.x.'
""";
    public const string DisableInternetSharing = """
$ErrorActionPreference = 'SilentlyContinue'
$DisabledIndex = [uint32]4294967295
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedAccess'

Set-ItemProperty -Path $RegPath -Name PublicIndex -Value $DisabledIndex -Type DWord
Set-ItemProperty -Path $RegPath -Name PrivateIndex -Value $DisabledIndex -Type DWord

Write-Output 'Internet sharing disabled'
""";
    public const string SyncClientPolicies = """
param(
    [Parameter(Mandatory = $true)]
    [string]$PayloadPath
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Normalize-Mac {
    param([string]$MacAddress)
    return (($MacAddress -replace '[^0-9A-Fa-f]', '').ToUpper())
}

function Remove-WiFiSharedPolicies {
    Get-NetFirewallRule -DisplayName 'WiFiShared Block Out *' -ErrorAction SilentlyContinue |
        Remove-NetFirewallRule -ErrorAction SilentlyContinue
    Get-NetFirewallRule -DisplayName 'WiFiShared Block In *' -ErrorAction SilentlyContinue |
        Remove-NetFirewallRule -ErrorAction SilentlyContinue
}

function Set-BlockRules {
    param(
        [string]$Mac,
        [string]$Ip
    )

    $outName = "WiFiShared Block Out $Mac"
    $inName = "WiFiShared Block In $Mac"

    $outRule = Get-NetFirewallRule -DisplayName $outName -ErrorAction SilentlyContinue
    if ($outRule) {
        Set-NetFirewallRule -DisplayName $outName -Enabled True
        Get-NetFirewallRule -DisplayName $outName |
            Get-NetFirewallAddressFilter |
            Set-NetFirewallAddressFilter -RemoteAddress $Ip
    }
    else {
        New-NetFirewallRule -DisplayName $outName `
            -Direction Outbound `
            -RemoteAddress $Ip `
            -Action Block `
            -Profile Any `
            -Enabled True | Out-Null
    }

    $inRule = Get-NetFirewallRule -DisplayName $inName -ErrorAction SilentlyContinue
    if ($inRule) {
        Set-NetFirewallRule -DisplayName $inName -Enabled True
        Get-NetFirewallRule -DisplayName $inName |
            Get-NetFirewallAddressFilter |
            Set-NetFirewallAddressFilter -RemoteAddress $Ip
    }
    else {
        New-NetFirewallRule -DisplayName $inName `
            -Direction Inbound `
            -RemoteAddress $Ip `
            -Action Block `
            -Profile Any `
            -Enabled True | Out-Null
    }
}

$payload = Get-Content -Path $PayloadPath -Raw -Encoding UTF8 | ConvertFrom-Json

if ($payload.clear -eq $true) {
    Remove-WiFiSharedPolicies
    exit 0
}

$desiredBlock = @{}

foreach ($client in @($payload.clients)) {
    $mac = Normalize-Mac $client.mac
    if ($mac.Length -eq 0) { continue }

    $ip = [string]$client.ip
    if ([string]::IsNullOrWhiteSpace($ip)) { continue }

    $policy = $null
    if ($payload.policies) {
        $policy = $payload.policies.$mac
        if (-not $policy) {
            $policy = $payload.policies.PSObject.Properties |
                Where-Object { (Normalize-Mac $_.Name) -eq $mac } |
                Select-Object -ExpandProperty Value -First 1
        }
    }

    if (-not $policy) { continue }

    if ($policy.blocked -eq $true) {
        $desiredBlock[$mac] = $ip
        Set-BlockRules -Mac $mac -Ip $ip
    }
}

Get-NetFirewallRule -DisplayName 'WiFiShared Block Out *' -ErrorAction SilentlyContinue | ForEach-Object {
    $mac = $_.DisplayName.Substring('WiFiShared Block Out '.Length)
    if (-not $desiredBlock.ContainsKey($mac)) {
        Remove-NetFirewallRule -DisplayName $_.DisplayName -ErrorAction SilentlyContinue
        Remove-NetFirewallRule -DisplayName ("WiFiShared Block In $mac") -ErrorAction SilentlyContinue
    }
}

exit 0
""";
    public const string EnableInternetSharingVbs = """
Option Explicit

Dim mgr, every, netConn, adapterName
Dim publicName, privateName
Dim publicConn, privateConn
Dim availableNames
Dim found

If WScript.Arguments.Count < 2 Then
    WScript.StdErr.WriteLine "Usage: EnableInternetSharing.vbs <publicConnectionName> <privateConnectionName>"
    WScript.Quit 1
End If

publicName = WScript.Arguments(0)
privateName = WScript.Arguments(1)

Set mgr = CreateObject("HNetCfg.HNetShare.1")

For Each every In mgr.EnumEveryConnection
    On Error Resume Next
    mgr.INetSharingConfigurationForINetConnection(every).DisableSharing
    On Error GoTo 0
Next

Set publicConn = Nothing
Set privateConn = Nothing
availableNames = ""

For Each every In mgr.EnumEveryConnection
    Set netConn = mgr.NetConnection(every)
    adapterName = netConn.Name
    availableNames = availableNames & adapterName & ", "
    If adapterName = publicName Then
        Set publicConn = every
    End If
    If adapterName = privateName Then
        Set privateConn = every
    End If
Next

If publicConn Is Nothing Then
    WScript.StdErr.WriteLine "Public adapter not found: " & publicName
    WScript.StdErr.WriteLine "Available: " & availableNames
    WScript.Quit 1
End If

If privateConn Is Nothing Then
    WScript.StdErr.WriteLine "Private adapter not found: " & privateName
    WScript.StdErr.WriteLine "Available: " & availableNames
    WScript.Quit 1
End If

mgr.INetSharingConfigurationForINetConnection(publicConn).EnableSharing 0
mgr.INetSharingConfigurationForINetConnection(privateConn).EnableSharing 1

WScript.Echo "ICS COM enabled: " & publicName & " -> " & privateName
""";
}


/// <summary>外部进程(netsh、PowerShell 等)执行工具。</summary>
internal static class ProcessRunner
{
    public sealed record ProcessResult(int ExitCode, string Output, string Error);

    public static async Task<ProcessResult> RunAsync(
        string fileName,
        string arguments,
        string? workingDirectory = null,
        int timeoutMs = 120000,
        CancellationToken cancellationToken = default)
    {
        using var process = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = arguments,
                WorkingDirectory = workingDirectory ?? Environment.CurrentDirectory,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true,
                StandardOutputEncoding = Encoding.UTF8,
                StandardErrorEncoding = Encoding.UTF8
            }
        };

        var outputBuilder = new StringBuilder();
        var errorBuilder = new StringBuilder();
        process.OutputDataReceived += (_, e) =>
        {
            if (e.Data != null)
                outputBuilder.AppendLine(e.Data);
        };
        process.ErrorDataReceived += (_, e) =>
        {
            if (e.Data != null)
                errorBuilder.AppendLine(e.Data);
        };

        if (!process.Start())
            throw new InvalidOperationException($"无法启动进程:{fileName}");

        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        using var registration = cancellationToken.Register(() =>
        {
            try
            {
                if (!process.HasExited)
                    process.Kill(entireProcessTree: true);
            }
            catch
            {
                // 忽略终止进程时的错误。
            }
        });

        var completed = await Task.Run(() => process.WaitForExit(timeoutMs), cancellationToken);
        if (!completed)
        {
            try
            {
                process.Kill(entireProcessTree: true);
            }
            catch
            {
                // 忽略。
            }

            throw new TimeoutException($"进程超时:{fileName} {arguments}");
        }

        return new ProcessResult(
            process.ExitCode,
            outputBuilder.ToString().Trim(),
            errorBuilder.ToString().Trim());
    }

    public static async Task<ProcessResult> RunPowerShellFileAsync(
        string scriptPath,
        IReadOnlyDictionary<string, string>? arguments = null,
        CancellationToken cancellationToken = default)
    {
        var argList = new List<string> { "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", scriptPath };
        if (arguments != null)
        {
            foreach (var pair in arguments)
                argList.Add($"-{pair.Key}");
            foreach (var pair in arguments)
                argList.Add(pair.Value);
        }

        var psiArgs = string.Join(" ", argList.Select(QuoteArgument));
        return await RunAsync("powershell.exe", psiArgs, cancellationToken: cancellationToken);
    }

    /// <summary>执行内嵌脚本:写入临时目录后调用 PowerShell。</summary>
    public static async Task<ProcessResult> RunEmbeddedPowerShellAsync(
        string scriptContent,
        IReadOnlyDictionary<string, string>? arguments = null,
        IReadOnlyDictionary<string, string>? companionFiles = null,
        string scriptFileName = "run.ps1",
        CancellationToken cancellationToken = default)
    {
        var tempDir = Path.Combine(Path.GetTempPath(), $"wifishared-{Guid.NewGuid():N}");
        Directory.CreateDirectory(tempDir);

        try
        {
            var scriptPath = Path.Combine(tempDir, scriptFileName);
            await File.WriteAllTextAsync(scriptPath, scriptContent, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), cancellationToken);

            if (companionFiles != null)
            {
                foreach (var (fileName, content) in companionFiles)
                {
                    var filePath = Path.Combine(tempDir, fileName);
                    await File.WriteAllTextAsync(filePath, content, cancellationToken);
                }
            }

            return await RunPowerShellFileAsync(scriptPath, arguments, cancellationToken);
        }
        finally
        {
            try
            {
                Directory.Delete(tempDir, recursive: true);
            }
            catch
            {
                // 忽略临时目录清理错误。
            }
        }
    }

    private static string QuoteArgument(string value) =>
        value.Contains(' ') || value.Contains('"')
            ? "\"" + value.Replace("\"", "\\\"") + "\""
            : value;
}

/// <summary>异常解包工具,将内部异常转为用户可读的错误信息。</summary>
public static class ExceptionHelper
{
    public static Exception Unwrap(Exception exception)
    {
        var current = exception;
        while (current.InnerException != null)
            current = current.InnerException;

        if (current is AggregateException aggregate && aggregate.InnerExceptions.Count == 1)
            return aggregate.InnerExceptions[0];

        return current;
    }

    public static string GetMessage(Exception exception)
    {
        var unwrapped = Unwrap(exception);
        var message = unwrapped.Message?.Trim();
        if (string.IsNullOrWhiteSpace(message))
            return "发生未知错误。";

        if (message.Contains("Hosted network", StringComparison.OrdinalIgnoreCase)
            || message.Contains("承载网络", StringComparison.OrdinalIgnoreCase))
            return "承载网络操作失败。请确认 USB WiFi 网卡已插入并以管理员身份运行。";

        if (message.Contains("not started", StringComparison.OrdinalIgnoreCase)
            || message.Contains("未启动", StringComparison.OrdinalIgnoreCase))
            return "热点尚未启动,请先启动 WiFi 路由器。";

        return message;
    }
}

/// <summary>客户端策略持久化存储(拉黑、限速)。</summary>
public sealed class ClientPolicyStore
{
    private readonly string _filePath;
    private readonly ConcurrentDictionary<string, ClientPolicy> _policies = new(StringComparer.OrdinalIgnoreCase);
    private readonly object _saveLock = new();

    public ClientPolicyStore()
    {
        var dir = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "WiFiShared");
        Directory.CreateDirectory(dir);
        _filePath = Path.Combine(dir, "client-policies.json");
        Load();
    }

    public ClientPolicy GetOrCreate(string macAddress)
    {
        var key = NormalizeMac(macAddress);
        return _policies.GetOrAdd(key, _ => new ClientPolicy());
    }

    public ClientPolicy? GetPolicy(string macAddress)
    {
        var key = NormalizeMac(macAddress);
        return _policies.TryGetValue(key, out var policy) ? policy : null;
    }

    public IReadOnlyDictionary<string, ClientPolicy> GetAll() => _policies;

    public void SetBlocked(string macAddress, bool blocked)
    {
        var policy = GetOrCreate(macAddress);
        policy.Blocked = blocked;
        Save();
    }

    public void SetBandwidthLimit(string macAddress, long? maxBytesPerSecond)
    {
        var policy = GetOrCreate(macAddress);
        policy.MaxBytesPerSecond = maxBytesPerSecond is > 0 ? maxBytesPerSecond : null;
        Save();
    }

    private void Load()
    {
        if (!File.Exists(_filePath))
            return;

        try
        {
            var json = File.ReadAllText(_filePath);
            var data = JsonSerializer.Deserialize<Dictionary<string, ClientPolicy>>(json);
            if (data == null)
                return;

            foreach (var pair in data)
                _policies[NormalizeMac(pair.Key)] = pair.Value;
        }
        catch
        {
            // 忽略损坏的策略文件。
        }
    }

    private void Save()
    {
        lock (_saveLock)
        {
            var json = JsonSerializer.Serialize(_policies, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(_filePath, json);
        }
    }

    public static string NormalizeMac(string macAddress) =>
        Regex.Replace(macAddress ?? string.Empty, "[^0-9A-Fa-f]", "").ToUpperInvariant();
}

/// <summary>客户端备注持久化存储。</summary>
public sealed class ClientRemarkStore
{
    private readonly string _filePath;
    private readonly ConcurrentDictionary<string, string> _remarks = new(StringComparer.OrdinalIgnoreCase);
    private readonly object _saveLock = new();

    public ClientRemarkStore()
    {
        var dir = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "WiFiShared");
        Directory.CreateDirectory(dir);
        _filePath = Path.Combine(dir, "client-remarks.json");
        Load();
    }

    public string? GetRemark(string macAddress)
    {
        var key = ClientPolicyStore.NormalizeMac(macAddress);
        return _remarks.TryGetValue(key, out var remark) ? remark : null;
    }

    public void SetRemark(string macAddress, string? remark)
    {
        var key = ClientPolicyStore.NormalizeMac(macAddress);
        if (string.IsNullOrWhiteSpace(remark))
            _remarks.TryRemove(key, out _);
        else
            _remarks[key] = remark.Trim();
        Save();
    }

    private void Load()
    {
        if (!File.Exists(_filePath))
            return;

        try
        {
            var json = File.ReadAllText(_filePath);
            var data = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
            if (data == null)
                return;

            foreach (var pair in data)
                _remarks[ClientPolicyStore.NormalizeMac(pair.Key)] = pair.Value;
        }
        catch
        {
            // 忽略损坏的备注文件。
        }
    }

    private void Save()
    {
        lock (_saveLock)
        {
            var json = JsonSerializer.Serialize(_remarks, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(_filePath, json);
        }
    }
}

/// <summary>通过 DNS 反向解析尝试获取客户端主机名作为备注。</summary>
public sealed class ClientRemarkService
{
    public async Task<string?> TryResolveHostnameAsync(string ipAddress)
    {
        if (string.IsNullOrWhiteSpace(ipAddress))
            return null;

        try
        {
            var entry = await Dns.GetHostEntryAsync(ipAddress);
            var host = entry.HostName?.Trim();
            if (string.IsNullOrWhiteSpace(host) || host.Equals(ipAddress, StringComparison.OrdinalIgnoreCase))
                return null;
            return host;
        }
        catch
        {
            return null;
        }
    }
}

/// <summary>通过 ARP 表解析客户端 MAC 与 IP 的对应关系。</summary>
public sealed class ClientAddressResolver
{
    private static readonly Regex ArpLineRegex = new(
        @"^\s*(?<ip>\d+\.\d+\.\d+\.\d+)\s+(?<mac>[0-9a-fA-F\-]+)",
        RegexOptions.Compiled);

    public async Task<Dictionary<string, string>> ResolveIpByMacAsync(IEnumerable<string> macAddresses)
    {
        var wanted = macAddresses
            .Select(ClientPolicyStore.NormalizeMac)
            .Where(m => m.Length >= 12)
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .ToHashSet(StringComparer.OrdinalIgnoreCase);

        var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        if (wanted.Count == 0)
            return result;

        var arp = await ProcessRunner.RunAsync("arp.exe", "-a");
        foreach (var line in arp.Output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
        {
            var match = ArpLineRegex.Match(line);
            if (!match.Success)
                continue;

            var ip = match.Groups["ip"].Value;
            var mac = ClientPolicyStore.NormalizeMac(match.Groups["mac"].Value);
            if (!wanted.Contains(mac))
                continue;

            result[mac] = ip;
        }

        return result;
    }

    public string? FindIpForMac(string macAddress, string subnetPrefix = "192.168.137.")
    {
        var wanted = ClientPolicyStore.NormalizeMac(macAddress);
        var arp = ProcessRunner.RunAsync("arp.exe", "-a").GetAwaiter().GetResult();
        foreach (var line in arp.Output.Split('\n', StringSplitOptions.RemoveEmptyEntries))
        {
            var match = ArpLineRegex.Match(line);
            if (!match.Success)
                continue;

            var ip = match.Groups["ip"].Value;
            if (!ip.StartsWith(subnetPrefix, StringComparison.Ordinal))
                continue;

            var mac = ClientPolicyStore.NormalizeMac(match.Groups["mac"].Value);
            if (mac.Equals(wanted, StringComparison.OrdinalIgnoreCase))
                return ip;
        }

        return null;
    }
}

/// <summary>枚举本机网络适配器并识别 WiFi、上行与虚拟网卡。</summary>
public sealed class NetworkDiscoveryService
{
  public IReadOnlyList<NetworkAdapterInfo> GetAdapters()
  {
    var result = new List<NetworkAdapterInfo>();
    foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
    {
      var description = nic.Description ?? string.Empty;
      var name = nic.Name ?? string.Empty;
      var isVirtual = nic.NetworkInterfaceType == NetworkInterfaceType.Ppp
          || description.Contains("Virtual", StringComparison.OrdinalIgnoreCase)
          || description.Contains("Hosted", StringComparison.OrdinalIgnoreCase)
          || description.Contains("Hyper-V", StringComparison.OrdinalIgnoreCase)
          || description.Contains("TAP", StringComparison.OrdinalIgnoreCase)
          || description.Contains("Miniport", StringComparison.OrdinalIgnoreCase)
          || description.Contains("Loopback", StringComparison.OrdinalIgnoreCase);

      var isWiFi = nic.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
          && !description.Contains("Hosted", StringComparison.OrdinalIgnoreCase)
          && !description.Contains("Direct", StringComparison.OrdinalIgnoreCase);

      var hasInternet = HasDefaultGateway(nic) ? "是" : "否";
      var status = nic.OperationalStatus switch
      {
        OperationalStatus.Up => "已连接",
        OperationalStatus.Down => "已断开",
        _ => nic.OperationalStatus.ToString()
      };

      result.Add(new NetworkAdapterInfo
      {
        Name = name,
        DisplayName = $"{name} ({description})",
        Description = description,
        Status = status,
        HasInternet = hasInternet,
        IsVirtual = isVirtual,
        IsWiFi = isWiFi
      });
    }

    return result;
  }

  public NetworkAdapterInfo? FindUpstreamAdapter()
  {
    return GetAdapters()
        .FirstOrDefault(a => a.Status == "已连接" && !a.IsVirtual && !a.IsWiFi && a.HasInternet == "是");
  }

  public async Task<NetworkAdapterInfo?> FindWiFiAdapterAsync()
  {
    await Task.Yield();
    return GetAdapters()
        .FirstOrDefault(a => a.IsWiFi && a.Status == "已连接")
        ?? GetAdapters().FirstOrDefault(a => a.IsWiFi);
  }

  private static bool HasDefaultGateway(NetworkInterface nic)
  {
    try
    {
      var props = nic.GetIPProperties();
      return props.GatewayAddresses.Any(g =>
          g.Address.AddressFamily == AddressFamily.InterNetwork
          && !IPAddress.IsLoopback(g.Address)
          && !g.Address.Equals(IPAddress.Any));
    }
    catch
    {
      return false;
    }
  }
}

/// <summary>热点虚拟网卡发现与 WinDivert 流量过滤规则生成。</summary>
public sealed class HotspotAdapterMonitor
{
  public int? HostedInterfaceIndex { get; private set; }
  public string? HostedInterfaceAlias { get; private set; }

  public async Task EnsureReadyAsync(TimeSpan timeout)
  {
    var deadline = DateTime.UtcNow + timeout;
    while (DateTime.UtcNow < deadline)
    {
      if (TryRefresh())
        return;
      await Task.Delay(500);
    }

    throw new InvalidOperationException("未找到已启动的热点虚拟网卡。");
  }

  public bool TryRefresh()
  {
    var nic = FindHotspotInterface();
    if (nic == null)
    {
      HostedInterfaceIndex = null;
      HostedInterfaceAlias = null;
      return false;
    }

    var ipv4 = nic.GetIPProperties().GetIPv4Properties();
    if (ipv4 == null)
      return false;

    HostedInterfaceIndex = ipv4.Index;
    HostedInterfaceAlias = nic.Name;
    return HostedInterfaceIndex is > 0;
  }

  /// <summary>查找移动热点或承载网络对应的虚拟网卡。</summary>
  public NetworkInterface? FindHotspotInterface()
  {
    return NetworkInterface.GetAllNetworkInterfaces()
        .Where(n => n.OperationalStatus == OperationalStatus.Up)
        .OrderByDescending(IsHotspotInterface)
        .ThenByDescending(n => HasHotspotGatewayAddress(n))
        .FirstOrDefault(IsHotspotInterface);
  }

  public (long Sent, long Received)? GetByteTotals(NetworkInterface networkInterface)
  {
    try
    {
      var stats = networkInterface.GetIPv4Statistics();
      return (stats.BytesSent, stats.BytesReceived);
    }
    catch
    {
      return null;
    }
  }

  public string BuildSubnetFilter(string? subnetPrefix = null)
  {
    if (string.IsNullOrWhiteSpace(subnetPrefix))
      subnetPrefix = GetHotspotSubnetPrefix() ?? "192.168.137.";

    return
        $"ip and ((ip.DstAddr >= {subnetPrefix}2 and ip.DstAddr <= {subnetPrefix}254) or " +
        $"(ip.SrcAddr >= {subnetPrefix}2 and ip.SrcAddr <= {subnetPrefix}254))";
  }

  private string? GetHotspotSubnetPrefix()
  {
    var nic = FindHotspotInterface();
    if (nic == null)
      return null;

    var address = nic.GetIPProperties().UnicastAddresses
        .FirstOrDefault(a => a.Address.AddressFamily == AddressFamily.InterNetwork
            && !IPAddress.IsLoopback(a.Address));
    if (address == null)
      return null;

    var bytes = address.Address.GetAddressBytes();
    if (bytes.Length != 4)
      return null;

    return $"{bytes[0]}.{bytes[1]}.{bytes[2]}.";
  }

  private static bool IsHotspotInterface(NetworkInterface networkInterface)
  {
    var description = networkInterface.Description ?? string.Empty;
    if (description.Contains("Wi-Fi Direct Virtual", StringComparison.OrdinalIgnoreCase)
        || description.Contains("Wi-Fi Direct 虚拟", StringComparison.OrdinalIgnoreCase)
        || description.Contains("Microsoft Hosted Network Virtual Adapter", StringComparison.OrdinalIgnoreCase)
        || description.Contains("Microsoft 托管网络虚拟适配器", StringComparison.OrdinalIgnoreCase)
        || description.Contains("Hosted Network Virtual", StringComparison.OrdinalIgnoreCase)
        || description.Contains("托管网络虚拟", StringComparison.OrdinalIgnoreCase))
    {
      return true;
    }

    return HasHotspotGatewayAddress(networkInterface);
  }

  private static bool HasHotspotGatewayAddress(NetworkInterface networkInterface)
  {
    return networkInterface.GetIPProperties().UnicastAddresses.Any(static address =>
        address.Address.AddressFamily == AddressFamily.InterNetwork
        && address.Address.ToString().StartsWith("192.168.137.", StringComparison.Ordinal));
  }
}

/// <summary>Windows 承载网络(Hosted Network)热点管理。</summary>
public sealed class HostedNetworkService
{
  private static readonly Regex MacRegex = new(
      @"(?:Client MAC address|客户端 MAC 地址)\s*[::]\s*(?<mac>[0-9A-Fa-f\-]+)",
      RegexOptions.Compiled | RegexOptions.IgnoreCase);

  public async Task<bool> IsSupportedAsync()
  {
    var result = await ProcessRunner.RunAsync("netsh.exe", "wlan show drivers");
    var text = result.Output;
    return text.Contains("Hosted network supported  : Yes", StringComparison.OrdinalIgnoreCase)
        || text.Contains("承载网络支持  : 是", StringComparison.OrdinalIgnoreCase)
        || text.Contains("Hosted network supported: Yes", StringComparison.OrdinalIgnoreCase);
  }

  public async Task ConfigureAsync(HotspotConfig config)
  {
    var escapedSsid = config.Ssid.Replace("\"", "\\\"");
    var escapedPassword = config.Password.Replace("\"", "\\\"");
    var args = $"wlan set hostednetwork mode=allow ssid=\"{escapedSsid}\" key=\"{escapedPassword}\"";
    var result = await ProcessRunner.RunAsync("netsh.exe", args);
    if (result.ExitCode != 0)
      throw new InvalidOperationException(result.Error.Length > 0 ? result.Error : result.Output);
  }

  public async Task StartAsync()
  {
    var result = await ProcessRunner.RunAsync("netsh.exe", "wlan start hostednetwork");
    if (result.ExitCode != 0 && !result.Output.Contains("already", StringComparison.OrdinalIgnoreCase))
      throw new InvalidOperationException(result.Error.Length > 0 ? result.Error : result.Output);
  }

  public async Task StopAsync()
  {
    await ProcessRunner.RunAsync("netsh.exe", "wlan stop hostednetwork");
  }

  public async Task<HostedNetworkSnapshot> GetSnapshotAsync()
  {
    var result = await ProcessRunner.RunAsync("cmd.exe", "/c chcp 65001>nul & netsh wlan show hostednetwork");
    var text = result.Output;
    var isRunning = text.Contains("Status                 : Started", StringComparison.OrdinalIgnoreCase)
        || text.Contains("状态                   : 已启动", StringComparison.OrdinalIgnoreCase)
        || text.Contains("Status: Started", StringComparison.OrdinalIgnoreCase);

    var isConfigured = text.Contains("SSID name", StringComparison.OrdinalIgnoreCase)
        || text.Contains("SSID 名称", StringComparison.OrdinalIgnoreCase);

    var ssidMatch = Regex.Match(text, @"(?:SSID name|SSID 名称)\s*[::]\s*""?(?<ssid>[^\r\n""]+)""?", RegexOptions.IgnoreCase);
    var ssid = ssidMatch.Success ? ssidMatch.Groups["ssid"].Value.Trim() : string.Empty;

    var maxClientsMatch = Regex.Match(text, @"(?:Max number of clients|最大客户端数)\s*[::]\s*(?<n>\d+)", RegexOptions.IgnoreCase);
    var maxClients = maxClientsMatch.Success ? int.Parse(maxClientsMatch.Groups["n"].Value) : 100;

    var macs = new List<string>();
    foreach (Match match in MacRegex.Matches(text))
      macs.Add(ClientPolicyStore.NormalizeMac(match.Groups["mac"].Value));

    return new HostedNetworkSnapshot(isRunning, isConfigured, ssid, maxClients, macs);
  }

  public sealed record HostedNetworkSnapshot(
      bool IsRunning,
      bool IsConfigured,
      string Ssid,
      int MaxClients,
      IReadOnlyList<string> ClientMacAddresses);
}

/// <summary>Internet 连接共享(ICS)启用与禁用。</summary>
public sealed class InternetSharingService
{
  public async Task EnableAsync(string? upstreamAdapterName = null)
  {
    var result = await ProcessRunner.RunEmbeddedPowerShellAsync(
        EmbeddedScripts.EnableInternetSharing,
        companionFiles: new Dictionary<string, string>
        {
            ["EnableInternetSharing.vbs"] = EmbeddedScripts.EnableInternetSharingVbs
        },
        scriptFileName: "EnableInternetSharing.ps1");
    if (result.ExitCode != 0)
      throw new InvalidOperationException(result.Error.Length > 0 ? result.Error : result.Output);
  }

  public async Task DisableAsync()
  {
    await ProcessRunner.RunEmbeddedPowerShellAsync(EmbeddedScripts.DisableInternetSharing);
  }
}

/// <summary>Windows 移动热点 API 封装。</summary>
public sealed class MobileHotspotService
{
  public bool IsAvailable()
  {
    try
    {
      var profile = NetworkInformation.GetInternetConnectionProfile();
      if (profile == null)
        return false;

      var manager = NetworkOperatorTetheringManager.CreateFromConnectionProfile(profile);
      return manager != null;
    }
    catch
    {
      return false;
    }
  }

  public async Task StartAsync(HotspotConfig config)
  {
    var profile = NetworkInformation.GetInternetConnectionProfile()
        ?? throw new InvalidOperationException("未找到可用的互联网连接,无法启动移动热点。");

    var manager = NetworkOperatorTetheringManager.CreateFromConnectionProfile(profile);
    var accessPoint = manager.GetCurrentAccessPointConfiguration();
    accessPoint.Ssid = config.Ssid;
    accessPoint.Passphrase = config.Password;
    await manager.ConfigureAccessPointAsync(accessPoint);

    if (manager.TetheringOperationalState == TetheringOperationalState.On)
      return;

    var result = await manager.StartTetheringAsync();
    if (result.Status != TetheringOperationStatus.Success)
      throw new InvalidOperationException($"移动热点启动失败:{result.Status}");
  }

  public async Task StopAsync()
  {
    var profile = NetworkInformation.GetInternetConnectionProfile();
    if (profile == null)
      return;

    var manager = NetworkOperatorTetheringManager.CreateFromConnectionProfile(profile);
    if (manager.TetheringOperationalState != TetheringOperationalState.On)
      return;

    var result = await manager.StopTetheringAsync();
    if (result.Status != TetheringOperationStatus.Success)
      throw new InvalidOperationException($"移动热点停止失败:{result.Status}");
  }

  public MobileHotspotSnapshot GetSnapshot()
  {
    var profile = NetworkInformation.GetInternetConnectionProfile();
    if (profile == null)
      return new MobileHotspotSnapshot(false, false, string.Empty, 0, Array.Empty<string>());

    var manager = NetworkOperatorTetheringManager.CreateFromConnectionProfile(profile);
    var isRunning = manager.TetheringOperationalState == TetheringOperationalState.On;
    var ssid = manager.GetCurrentAccessPointConfiguration().Ssid ?? string.Empty;
    var maxClients = (int)manager.MaxClientCount;
    var macs = manager.GetTetheringClients()
        .Select(c => ClientPolicyStore.NormalizeMac(c.MacAddress))
        .Where(m => m.Length >= 12)
        .Distinct(StringComparer.OrdinalIgnoreCase)
        .ToList();

    return new MobileHotspotSnapshot(isRunning, true, ssid, maxClients, macs);
  }

  public sealed record MobileHotspotSnapshot(
      bool IsRunning,
      bool IsConfigured,
      string Ssid,
      int MaxClients,
      IReadOnlyList<string> ClientMacAddresses);
}

/// <summary>统计热点网卡流量并估算各客户端上下行速率。</summary>
public sealed class ClientTrafficTracker
{
  private readonly object _sync = new();
  private DateTime? _lastSampleTime;
  private (long Sent, long Received)? _lastAdapterTotals;
  private readonly Dictionary<string, long> _sessionBytesByMac = new(StringComparer.OrdinalIgnoreCase);
  private bool _active;

  public void Start()
  {
    lock (_sync)
    {
      _active = true;
      _lastSampleTime = null;
      _lastAdapterTotals = null;
      _sessionBytesByMac.Clear();
    }
  }

  public void EnsureStarted()
  {
    lock (_sync)
    {
      if (!_active)
        Start();
    }
  }

  public void Stop()
  {
    lock (_sync)
    {
      _active = false;
      _lastSampleTime = null;
      _lastAdapterTotals = null;
      _sessionBytesByMac.Clear();
    }
  }

  /// <summary>根据热点网卡总流量,按在线设备数均分估算各客户端速率与累计流量。</summary>
  public HotspotStatus Enrich(HotspotStatus status, HotspotAdapterMonitor monitor)
  {
    if (!_active || !status.IsRunning || status.Clients.Count == 0)
    {
      if (!_active || !status.IsRunning)
        Stop();
      return status;
    }

    monitor.TryRefresh();
    var adapter = monitor.FindHotspotInterface();
    var adapterTotals = adapter != null ? monitor.GetByteTotals(adapter) : null;
    var now = DateTime.UtcNow;

    lock (_sync)
    {
      var clientCount = status.Clients.Count;
      var downloadRates = new double?[clientCount];
      var uploadRates = new double?[clientCount];
      var sessionBytes = new long?[clientCount];
      var hasRates = false;

      if (adapterTotals.HasValue && _lastAdapterTotals.HasValue && _lastSampleTime.HasValue)
      {
        var elapsedSeconds = (now - _lastSampleTime.Value).TotalSeconds;
        if (elapsedSeconds > 0.2)
        {
          var sentDelta = GetPositiveDelta(adapterTotals.Value.Sent, _lastAdapterTotals.Value.Sent);
          var receivedDelta = GetPositiveDelta(adapterTotals.Value.Received, _lastAdapterTotals.Value.Received);
          var downloadRate = sentDelta / elapsedSeconds / clientCount;
          var uploadRate = receivedDelta / elapsedSeconds / clientCount;

          for (var index = 0; index < clientCount; index++)
          {
            downloadRates[index] = downloadRate;
            uploadRates[index] = uploadRate;
          }

          hasRates = sentDelta + receivedDelta > 0;
        }
      }

      if (adapterTotals.HasValue && _lastAdapterTotals.HasValue)
      {
        var sentDelta = GetPositiveDelta(adapterTotals.Value.Sent, _lastAdapterTotals.Value.Sent);
        var receivedDelta = GetPositiveDelta(adapterTotals.Value.Received, _lastAdapterTotals.Value.Received);
        var trafficDelta = (sentDelta + receivedDelta) / clientCount;

        if (trafficDelta > 0)
        {
          for (var index = 0; index < clientCount; index++)
          {
            var mac = ClientPolicyStore.NormalizeMac(status.Clients[index].MacAddress);
            if (mac.Length == 0)
              continue;

            if (!_sessionBytesByMac.TryGetValue(mac, out var total))
              total = 0;

            total += trafficDelta;
            _sessionBytesByMac[mac] = total;
            sessionBytes[index] = total;
          }
        }
      }

      var activeMacs = status.Clients
          .Select(client => ClientPolicyStore.NormalizeMac(client.MacAddress))
          .Where(mac => mac.Length > 0)
          .ToHashSet(StringComparer.OrdinalIgnoreCase);

      foreach (var mac in _sessionBytesByMac.Keys.Where(mac => !activeMacs.Contains(mac)).ToList())
        _sessionBytesByMac.Remove(mac);

      for (var index = 0; index < clientCount; index++)
      {
        var mac = ClientPolicyStore.NormalizeMac(status.Clients[index].MacAddress);
        if (mac.Length > 0 && _sessionBytesByMac.TryGetValue(mac, out var total))
          sessionBytes[index] = total;
      }

      _lastSampleTime = now;
      _lastAdapterTotals = adapterTotals;

      var clients = status.Clients
          .Select((client, index) => new ConnectedClient
          {
            MacAddress = client.MacAddress,
            Remark = client.Remark,
            IsBlocked = client.IsBlocked,
            MaxBytesPerSecond = client.MaxBytesPerSecond,
            DownloadRateBytesPerSec = hasRates ? downloadRates[index] : null,
            UploadRateBytesPerSec = hasRates ? uploadRates[index] : null,
            SessionBytes = sessionBytes[index] is > 0 ? sessionBytes[index] : null
          })
          .ToList();

      return new HotspotStatus
      {
        IsRunning = status.IsRunning,
        IsConfigured = status.IsConfigured,
        Ssid = status.Ssid,
        MaxClients = status.MaxClients,
        ConnectedClients = status.ConnectedClients,
        Clients = clients
      };
    }
  }

  private static long GetPositiveDelta(long current, long previous)
  {
    var delta = current - previous;
    return delta >= 0 ? delta : 0;
  }
}

/// <summary>基于 WinDivert 的数据包层带宽限速与拉黑拦截。</summary>
public sealed class ClientBandwidthLimiter : IDisposable
{
  private readonly ConcurrentDictionary<string, TokenBucket> _buckets = new(StringComparer.OrdinalIgnoreCase);
  private readonly ConcurrentDictionary<string, byte> _blockedIps = new(StringComparer.OrdinalIgnoreCase);
  private readonly object _sync = new();
  private readonly object _startLock = new();
  private CancellationTokenSource? _cts;
  private Task[]? _workerTasks;
  private string _trafficFilter = BuildDefaultHotspotFilter();
  private bool _disposed;

  public string? LastError { get; private set; }
  public bool IsRunning => _workerTasks is { Length: > 0 } && _workerTasks.Any(t => !t.IsCompleted);

  public void UpdatePolicies(
      IReadOnlyDictionary<string, long> bandwidthLimits,
      IReadOnlyCollection<string> blockedIps,
      string? trafficFilter = null)
  {
    ObjectDisposedException.ThrowIf(_disposed, this);

    if (!string.IsNullOrWhiteSpace(trafficFilter))
      _trafficFilter = trafficFilter;

    lock (_sync)
    {
      _blockedIps.Clear();
      foreach (var ip in blockedIps.Where(ip => !string.IsNullOrWhiteSpace(ip)))
        _blockedIps[ip] = 0;

      var nextBuckets = new ConcurrentDictionary<string, TokenBucket>(StringComparer.OrdinalIgnoreCase);
      foreach (var (ip, bytesPerSecond) in bandwidthLimits)
      {
        if (bytesPerSecond <= 0 || _blockedIps.ContainsKey(ip))
          continue;

        if (_buckets.TryGetValue(ip, out var existing))
        {
          existing.MaxBytesPerSecond = bytesPerSecond;
          nextBuckets[ip] = existing;
        }
        else
        {
          nextBuckets[ip] = new TokenBucket(bytesPerSecond);
        }
      }

      _buckets.Clear();
      foreach (var pair in nextBuckets)
        _buckets[pair.Key] = pair.Value;
    }

    if (_blockedIps.IsEmpty && _buckets.IsEmpty)
    {
      StopWorkers();
      LastError = null;
      return;
    }

    EnsureWorkersRunning();
  }

  public void SetBlocked(string ipAddress, bool blocked)
  {
    if (string.IsNullOrWhiteSpace(ipAddress))
      return;

    var limits = _buckets.ToDictionary(p => p.Key, p => p.Value.MaxBytesPerSecond, StringComparer.OrdinalIgnoreCase);
    var blockedList = _blockedIps.Keys.ToList();
    if (blocked)
    {
      if (!blockedList.Contains(ipAddress, StringComparer.OrdinalIgnoreCase))
        blockedList.Add(ipAddress);
      limits.Remove(ipAddress);
    }
    else
    {
      blockedList.RemoveAll(ip => ip.Equals(ipAddress, StringComparison.OrdinalIgnoreCase));
    }

    UpdatePolicies(limits, blockedList);
  }

  public void SetLimit(string ipAddress, long? maxBytesPerSecond)
  {
    if (string.IsNullOrWhiteSpace(ipAddress))
      return;

    var limits = _buckets.ToDictionary(p => p.Key, p => p.Value.MaxBytesPerSecond, StringComparer.OrdinalIgnoreCase);
    if (maxBytesPerSecond is > 0)
      limits[ipAddress] = maxBytesPerSecond.Value;
    else
      limits.Remove(ipAddress);

    UpdatePolicies(limits, _blockedIps.Keys.ToList());
  }

  public void ClearPolicies()
  {
    lock (_sync)
    {
      _buckets.Clear();
      _blockedIps.Clear();
      StopWorkers();
      LastError = null;
    }
  }

  public void EnsureRunning(string filter)
  {
    ObjectDisposedException.ThrowIf(_disposed, this);
    if (!string.IsNullOrWhiteSpace(filter))
      _trafficFilter = filter;

    if (IsRunning)
      return;

    if (_blockedIps.IsEmpty && _buckets.IsEmpty)
      return;

    EnsureWorkersRunning();
  }

  public void Start(string filter)
  {
    if (!string.IsNullOrWhiteSpace(filter))
      _trafficFilter = filter;
    EnsureWorkersRunning();
  }

  public void Stop() => ClearPolicies();

  public void Dispose()
  {
    if (_disposed)
      return;

    _disposed = true;
    ClearPolicies();
  }

  private void EnsureWorkersRunning()
  {
    lock (_startLock)
    {
      if (_workerTasks is { Length: > 0 } && _workerTasks.Any(t => !t.IsCompleted))
        return;

      StopWorkersLocked();

      _cts = new CancellationTokenSource();
      var filter = _trafficFilter;
      var token = _cts.Token;
      _workerTasks =
      [
        Task.Run(() => RunWorkerLoopAsync(WinDivertLayer.Network, filter, token), token),
        Task.Run(() => RunWorkerLoopAsync(WinDivertLayer.Forward, filter, token), token)
      ];
    }
  }

  private void StopWorkers()
  {
    lock (_startLock)
      StopWorkersLocked();
  }

  private void StopWorkersLocked()
  {
    var cts = _cts;
    var tasks = _workerTasks;
    _cts = null;
    _workerTasks = null;

    if (cts == null)
      return;

    try
    {
      cts.Cancel();
    }
    catch
    {
      // 忽略取消错误。
    }

    if (tasks != null)
    {
      try
      {
        Task.WaitAll(tasks, TimeSpan.FromSeconds(3));
      }
      catch
      {
        // 忽略关闭超时。
      }
    }

    cts.Dispose();
  }

  private async Task RunWorkerLoopAsync(
      WinDivertLayer layer,
      string filter,
      CancellationToken cancellationToken)
  {
    IntPtr handle = IntPtr.Zero;

    try
    {
      handle = WinDivert.WinDivertOpen(filter, layer, 0, WinDivertOpenFlags.None);
      if (handle == IntPtr.Zero)
      {
        LastError = $"WinDivert 启动失败({layer},错误码 {Marshal.GetLastWin32Error()})。请确认以管理员身份运行。";
        return;
      }

      LastError = null;
      using var packetBuffer = new WinDivertBuffer(0xFFFF);

      while (!cancellationToken.IsCancellationRequested)
      {
        var address = new WinDivertAddress();
        uint packetLength = 0;
        if (!WinDivert.WinDivertRecv(handle, packetBuffer, ref address, ref packetLength))
        {
          await Task.Delay(1, cancellationToken);
          continue;
        }

        if (ShouldAllowPacket(packetBuffer, packetLength))
          WinDivert.WinDivertSend(handle, packetBuffer, packetLength, ref address);
      }
    }
    catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
    {
      // 正常退出。
    }
    catch (Exception ex)
    {
      LastError = $"流量策略运行失败({layer}):{ex.Message}";
    }
    finally
    {
      if (handle != IntPtr.Zero)
        WinDivert.WinDivertClose(handle);
    }
  }

  private bool ShouldAllowPacket(WinDivertBuffer packetBuffer, uint packetLength)
  {
    if (packetLength < 20)
      return true;

    var packet = packetBuffer.ToReadOnlyMemory(packetLength).Span;
    if ((packet[0] >> 4) != 4)
      return true;

    var src = FormatIp(packet.Slice(12, 4));
    var dst = FormatIp(packet.Slice(16, 4));

    lock (_sync)
    {
      if (_blockedIps.IsEmpty && _buckets.IsEmpty)
        return true;

      if (_blockedIps.ContainsKey(src) || _blockedIps.ContainsKey(dst))
        return false;

      if (_buckets.TryGetValue(dst, out var downloadBucket) && !downloadBucket.TryConsume(packetLength))
        return false;

      if (_buckets.TryGetValue(src, out var uploadBucket) && !uploadBucket.TryConsume(packetLength))
        return false;
    }

    return true;
  }

  private static string FormatIp(ReadOnlySpan<byte> bytes) =>
      $"{bytes[0]}.{bytes[1]}.{bytes[2]}.{bytes[3]}";

  private static string BuildDefaultHotspotFilter() =>
      "ip and ((ip.DstAddr >= 192.168.137.2 and ip.DstAddr <= 192.168.137.254) or " +
      "(ip.SrcAddr >= 192.168.137.2 and ip.SrcAddr <= 192.168.137.254))";

  private sealed class TokenBucket
  {
    private double _tokens;
    private DateTime _lastRefillUtc = DateTime.UtcNow;

    public TokenBucket(long maxBytesPerSecond)
    {
      MaxBytesPerSecond = maxBytesPerSecond;
    }

    public long MaxBytesPerSecond { get; set; }

    public bool TryConsume(uint packetLength)
    {
      Refill();

      if (_tokens >= packetLength)
      {
        _tokens -= packetLength;
        return true;
      }

      return false;
    }

    private void Refill()
    {
      var now = DateTime.UtcNow;
      var elapsedSeconds = (now - _lastRefillUtc).TotalSeconds;
      _lastRefillUtc = now;

      if (elapsedSeconds <= 0)
        return;

      _tokens = Math.Min(MaxBytesPerSecond, _tokens + elapsedSeconds * MaxBytesPerSecond);
    }
  }
}

/// <summary>将客户端策略同步到防火墙脚本与 WinDivert 限速器。</summary>
public sealed class ClientPolicyEnforcer
{
  private static readonly JsonSerializerOptions JsonOptions = new()
  {
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
  };

  private readonly ClientPolicyStore _policyStore;
  private readonly ClientAddressResolver _addressResolver;
  private readonly ClientBandwidthLimiter _bandwidthLimiter;
  private string? _lastSyncFingerprint;

  public string? BandwidthLimiterError => _bandwidthLimiter.LastError;
  public bool IsBandwidthLimiterRunning => _bandwidthLimiter.IsRunning;

  public ClientPolicyEnforcer(
      ClientPolicyStore policyStore,
      ClientAddressResolver addressResolver,
      ClientBandwidthLimiter bandwidthLimiter)
  {
    _policyStore = policyStore;
    _addressResolver = addressResolver;
    _bandwidthLimiter = bandwidthLimiter;
  }

  public async Task SyncAsync(
      IReadOnlyList<string> clientMacAddresses,
      string trafficFilter,
      bool clear = false,
      bool force = false)
  {
    if (clear)
    {
      _lastSyncFingerprint = null;
      _bandwidthLimiter.ClearPolicies();
      await RunSyncScriptAsync(new { clear = true });
      return;
    }

    var targetMacs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
    foreach (var mac in clientMacAddresses)
    {
      var normalized = ClientPolicyStore.NormalizeMac(mac);
      if (normalized.Length >= 12)
        targetMacs.Add(normalized);
    }

    foreach (var (mac, policy) in _policyStore.GetAll())
    {
      if (policy.Blocked || policy.MaxBytesPerSecond is > 0)
        targetMacs.Add(mac);
    }

    var ipMap = await _addressResolver.ResolveIpByMacAsync(targetMacs);
    var policiesPayload = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
    var bandwidthLimits = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
    var blockedIps = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

    foreach (var mac in targetMacs)
    {
      var policy = _policyStore.GetPolicy(mac);
      if (policy == null)
        continue;

      policiesPayload[mac] = new
      {
        blocked = policy.Blocked,
        maxBytesPerSecond = policy.MaxBytesPerSecond
      };

      if (!ipMap.TryGetValue(mac, out var ip) || string.IsNullOrWhiteSpace(ip))
        continue;

      if (policy.Blocked)
        blockedIps.Add(ip);

      if (policy.MaxBytesPerSecond is { } limit && limit > 0 && !policy.Blocked)
        bandwidthLimits[ip] = limit;
    }

    var payload = new
    {
      clients = ipMap.Select(pair => new { mac = pair.Key, ip = pair.Value }).ToList(),
      policies = policiesPayload
    };

    var fingerprint = JsonSerializer.Serialize(payload, JsonOptions);
    if (!force && string.Equals(fingerprint, _lastSyncFingerprint, StringComparison.Ordinal))
      return;

    _bandwidthLimiter.UpdatePolicies(bandwidthLimits, blockedIps, trafficFilter);
    if (!string.IsNullOrWhiteSpace(_bandwidthLimiter.LastError) && force)
      throw new InvalidOperationException(_bandwidthLimiter.LastError);

    if (force && blockedIps.Count == 0 && bandwidthLimits.Count == 0
        && _policyStore.GetAll().Values.Any(p => p.Blocked || p.MaxBytesPerSecond is > 0))
    {
      throw new InvalidOperationException("未能解析设备 IP,请稍后重试或刷新设备列表。");
    }

    try
    {
      await RunSyncScriptAsync(payload);
    }
    catch
    {
      // 防火墙规则为尽力而为;WinDivert 已负责主要拦截。
    }

    _lastSyncFingerprint = fingerprint;
  }

  private static async Task RunSyncScriptAsync(object payload)
  {
    var tempPath = Path.Combine(Path.GetTempPath(), $"wifishared-policies-{Guid.NewGuid():N}.json");
    try
    {
      var json = JsonSerializer.Serialize(payload, JsonOptions);
      await File.WriteAllTextAsync(tempPath, json);
      var result = await ProcessRunner.RunEmbeddedPowerShellAsync(
          EmbeddedScripts.SyncClientPolicies,
          new Dictionary<string, string> { ["PayloadPath"] = tempPath },
          scriptFileName: "SyncClientPolicies.ps1");
      if (result.ExitCode != 0)
        throw new InvalidOperationException(result.Error.Length > 0 ? result.Error : result.Output);
    }
    finally
    {
      try
      {
        if (File.Exists(tempPath))
          File.Delete(tempPath);
      }
      catch
      {
        // 忽略临时文件删除错误。
      }
    }
  }
}

/// <summary>WiFi 路由器核心服务,统一调度热点、共享、策略与流量统计。</summary>
public sealed class WiFiRouterService
{
  private readonly HostedNetworkService _hostedNetworkService = new();
  private readonly MobileHotspotService _mobileHotspotService = new();
  private readonly InternetSharingService _internetSharingService = new();
  private readonly NetworkDiscoveryService _networkDiscovery = new();
  private readonly HotspotAdapterMonitor _hotspotAdapterMonitor = new();
  private readonly ClientPolicyStore _policyStore = new();
  private readonly ClientRemarkStore _remarkStore = new();
  private readonly ClientRemarkService _remarkService = new();
  private readonly ClientAddressResolver _addressResolver = new();
  private readonly ClientTrafficTracker _trafficTracker = new();
  private readonly ClientBandwidthLimiter _bandwidthLimiter = new();
  private readonly ClientPolicyEnforcer _policyEnforcer;

  private bool _useMobileHotspot;

  public WiFiRouterService()
  {
    _policyEnforcer = new ClientPolicyEnforcer(_policyStore, _addressResolver, _bandwidthLimiter);
  }

  public NetworkDiscoveryService NetworkDiscovery => _networkDiscovery;
  public ClientRemarkStore RemarkStore => _remarkStore;

  public async Task<bool> IsSupportedAsync() => await _hostedNetworkService.IsSupportedAsync();

  public async Task<HotspotStatus> GetStatusAsync()
  {
    var status = await QueryStatusCoreAsync();

    if (status.IsRunning)
      await SyncPoliciesForStatusAsync(status, force: false);

    return status;
  }

  private async Task<HotspotStatus> QueryStatusCoreAsync()
  {
    HotspotStatus status;
    if (_useMobileHotspot)
    {
      var snapshot = _mobileHotspotService.GetSnapshot();
      status = await BuildStatusFromMacsAsync(
          snapshot.IsRunning,
          snapshot.IsConfigured,
          snapshot.Ssid,
          snapshot.MaxClients,
          snapshot.ClientMacAddresses);
    }
    else
    {
      var hosted = await _hostedNetworkService.GetSnapshotAsync();
      status = await BuildStatusFromMacsAsync(
          hosted.IsRunning,
          hosted.IsConfigured,
          hosted.Ssid,
          hosted.MaxClients,
          hosted.ClientMacAddresses);
    }

    if (status.IsRunning)
    {
      _hotspotAdapterMonitor.TryRefresh();
      _trafficTracker.EnsureStarted();
    }

    return _trafficTracker.Enrich(status, _hotspotAdapterMonitor);
  }

  private async Task SyncPoliciesForStatusAsync(HotspotStatus status, bool force)
  {
    _hotspotAdapterMonitor.TryRefresh();
    var filter = _hotspotAdapterMonitor.BuildSubnetFilter();
    await _policyEnforcer.SyncAsync(
        status.Clients.Select(c => c.MacAddress).ToList(),
        filter,
        force: force);
  }

  public async Task StartRouterAsync(HotspotConfig config, string? upstreamAdapterName = null)
  {
    if (string.IsNullOrWhiteSpace(config.Ssid))
      throw new InvalidOperationException("请输入热点名称。");

    if (config.Password.Length < 8)
      throw new InvalidOperationException("WiFi 密码至少需要 8 位。");

    if (_mobileHotspotService.IsAvailable())
    {
      await _mobileHotspotService.StartAsync(config);
      _useMobileHotspot = true;
      await Task.Delay(2000);
      if (_hotspotAdapterMonitor.TryRefresh())
      {
        _trafficTracker.Start();
        await SyncPoliciesForStatusAsync(
            await QueryStatusCoreAsync(),
            force: true);
      }
    }
    else
    {
      await _hostedNetworkService.ConfigureAsync(config);
      await _hostedNetworkService.StartAsync();
      await _internetSharingService.EnableAsync(upstreamAdapterName);
      _useMobileHotspot = false;
      await _hotspotAdapterMonitor.EnsureReadyAsync(TimeSpan.FromSeconds(20));
      _trafficTracker.Start();
      await SyncPoliciesForStatusAsync(
          await QueryStatusCoreAsync(),
          force: true);
    }

    await SyncPoliciesSafeAsync();
  }

  public async Task StopRouterAsync()
  {
    try
    {
      if (_useMobileHotspot)
        await _mobileHotspotService.StopAsync();
      else
      {
        await _internetSharingService.DisableAsync();
        await _hostedNetworkService.StopAsync();
      }
    }
    catch
    {
      // 忽略停止热点时的错误。
    }

    _bandwidthLimiter.Stop();
    _trafficTracker.Stop();

    try
    {
      await _policyEnforcer.SyncAsync(Array.Empty<string>(), string.Empty, clear: true);
    }
    catch
    {
      // 忽略清理过程中的错误。
    }
  }

  public async Task SetClientBlockedAsync(string macAddress, bool blocked)
  {
    _policyStore.SetBlocked(macAddress, blocked);
    var status = await QueryStatusCoreAsync();
    await SyncPoliciesForStatusAsync(status, force: true);
  }

  public async Task SetClientBandwidthLimitAsync(string macAddress, long? maxBytesPerSecond)
  {
    _policyStore.SetBandwidthLimit(macAddress, maxBytesPerSecond);
    var status = await QueryStatusCoreAsync();
    await SyncPoliciesForStatusAsync(status, force: true);
  }

  private async Task<HotspotStatus> BuildStatusFromMacsAsync(
      bool isRunning,
      bool isConfigured,
      string ssid,
      int maxClients,
      IReadOnlyList<string> macAddresses)
  {
    var ipMap = await _addressResolver.ResolveIpByMacAsync(macAddresses);
    var clients = new List<ConnectedClient>();

    foreach (var mac in macAddresses)
    {
      var normalized = ClientPolicyStore.NormalizeMac(mac);
      var formattedMac = FormatMac(normalized);
      var remark = _remarkStore.GetRemark(normalized);
      if (string.IsNullOrWhiteSpace(remark))
      {
        var ip = ipMap.GetValueOrDefault(normalized);
        if (ip != null)
          remark = await _remarkService.TryResolveHostnameAsync(ip);
      }

      var policy = _policyStore.GetPolicy(normalized);

      clients.Add(new ConnectedClient
      {
        MacAddress = formattedMac,
        Remark = remark,
        IsBlocked = policy?.Blocked ?? false,
        MaxBytesPerSecond = policy?.MaxBytesPerSecond
      });
    }

    return new HotspotStatus
    {
      IsRunning = isRunning,
      IsConfigured = isConfigured,
      Ssid = ssid,
      ConnectedClients = clients.Count,
      MaxClients = maxClients,
      Clients = clients
    };
  }

  private async Task SyncPoliciesSafeAsync()
  {
    try
    {
      var status = await QueryStatusCoreAsync();
      if (status.IsRunning)
        await SyncPoliciesForStatusAsync(status, force: true);
    }
    catch
    {
      // 策略同步失败不应影响状态轮询。
    }
  }

  private static string FormatMac(string normalizedMac)
  {
    if (normalizedMac.Length != 12)
      return normalizedMac;

    return string.Join("-", Enumerable.Range(0, 6).Select(i => normalizedMac.Substring(i * 2, 2)));
  }
}

/// <summary>系统托盘图标服务,支持最小化到托盘与右键菜单操作。</summary>
public sealed class TrayIconService : IDisposable
{
  private readonly Forms.NotifyIcon _notifyIcon;
  private bool _disposed;

  public TrayIconService(string tooltip, Action onShow, Func<Task> onExitAsync)
  {
    _notifyIcon = new Forms.NotifyIcon
    {
      Text = tooltip,
      Icon = LoadIcon(),
      Visible = true
    };

    _notifyIcon.DoubleClick += (_, _) => onShow();

    var menu = new Forms.ContextMenuStrip();
    menu.Items.Add("显示主窗口", null, (_, _) => onShow());
    menu.Items.Add("退出", null, (_, _) => _ = onExitAsync());
    _notifyIcon.ContextMenuStrip = menu;
  }

  private static Icon LoadIcon()
  {
    var uri = new Uri("pack://application:,,,/Assets/app.ico", UriKind.Absolute);
    var stream = System.Windows.Application.GetResourceStream(uri)?.Stream
        ?? throw new InvalidOperationException("未找到程序图标 Assets/app.ico。");

    using (stream)
    using (var sourceIcon = new Icon(stream))
    {
      var traySize = Forms.SystemInformation.SmallIconSize;
      return new Icon(sourceIcon, traySize.Width, traySize.Height);
    }
  }

  public void Dispose()
  {
    if (_disposed)
      return;

    _disposed = true;
    _notifyIcon.Visible = false;
    _notifyIcon.Dispose();
  }
}

/// <summary>编辑客户端备注的对话框。</summary>
public sealed class EditClientRemarkDialog : Window
{
  private readonly System.Windows.Controls.TextBox _remarkTextBox;

  public string Remark { get; private set; } = string.Empty;

  public EditClientRemarkDialog(string macAddress, string? currentRemark)
  {
    Title = "编辑备注";
    Width = 420;
    Height = 220;
    WindowStartupLocation = WindowStartupLocation.CenterOwner;
    ResizeMode = ResizeMode.NoResize;
    Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xEE, 0xF2, 0xF7));

    var root = new Grid { Margin = new Thickness(20) };
    root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
    root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

    var macLabel = new TextBlock { Text = "MAC 地址", Margin = new Thickness(0, 0, 0, 6) };
    var macText = new TextBlock
    {
      Text = macAddress,
      FontFamily = new System.Windows.Media.FontFamily("Consolas"),
      Margin = new Thickness(0, 0, 0, 12)
    };

    var remarkLabel = new TextBlock { Text = "备注", Margin = new Thickness(0, 0, 0, 6) };
    _remarkTextBox = new System.Windows.Controls.TextBox
    {
      Text = currentRemark ?? string.Empty,
      Padding = new Thickness(10, 8, 10, 8),
      Margin = new Thickness(0, 0, 0, 16)
    };

    var buttons = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
    var saveButton = new System.Windows.Controls.Button { Content = "保存", MinWidth = 88, Margin = new Thickness(0, 0, 8, 0), Padding = new Thickness(12, 6, 12, 6) };
    var cancelButton = new System.Windows.Controls.Button { Content = "取消", MinWidth = 88, Padding = new Thickness(12, 6, 12, 6) };
    saveButton.Click += (_, _) =>
    {
      Remark = _remarkTextBox.Text.Trim();
      DialogResult = true;
    };
    cancelButton.Click += (_, _) => DialogResult = false;
    buttons.Children.Add(saveButton);
    buttons.Children.Add(cancelButton);

    Grid.SetRow(macLabel, 0);
    Grid.SetRow(macText, 1);
    Grid.SetRow(remarkLabel, 2);
    Grid.SetRow(_remarkTextBox, 3);
    Grid.SetRow(buttons, 4);

    root.Children.Add(macLabel);
    root.Children.Add(macText);
    root.Children.Add(remarkLabel);
    root.Children.Add(_remarkTextBox);
    root.Children.Add(buttons);
    Content = root;

    Loaded += (_, _) =>
    {
      _remarkTextBox.Focus();
      _remarkTextBox.SelectAll();
    };
  }
}

/// <summary>设置客户端带宽限速的对话框。</summary>
public sealed class EditClientBandwidthDialog : Window
{
  private readonly System.Windows.Controls.ComboBox _presetComboBox;
  private readonly System.Windows.Controls.TextBox _customTextBox;

  public long? MaxBytesPerSecond { get; private set; }

  public EditClientBandwidthDialog(string macAddress, long? currentLimitBytesPerSecond)
  {
    Title = "设置限速";
    Width = 460;
    Height = 280;
    WindowStartupLocation = WindowStartupLocation.CenterOwner;
    ResizeMode = ResizeMode.NoResize;
    Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0xEE, 0xF2, 0xF7));

    var root = new Grid { Margin = new Thickness(20) };
    for (var i = 0; i < 6; i++)
      root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });

    var macLabel = new TextBlock { Text = "MAC 地址", Margin = new Thickness(0, 0, 0, 6) };
    var macText = new TextBlock
    {
      Text = macAddress,
      FontFamily = new System.Windows.Media.FontFamily("Consolas"),
      Margin = new Thickness(0, 0, 0, 12)
    };

    var presetLabel = new TextBlock { Text = "限速预设", Margin = new Thickness(0, 0, 0, 6) };
    _presetComboBox = new System.Windows.Controls.ComboBox { Margin = new Thickness(0, 0, 0, 12) };
    _presetComboBox.Items.Add(CreatePresetItem("不限制", null));
    _presetComboBox.Items.Add(CreatePresetItem("5 KB/s", 5120));
    _presetComboBox.Items.Add(CreatePresetItem("10 KB/s", 10240));
    _presetComboBox.Items.Add(CreatePresetItem("20 KB/s", 20480));
    _presetComboBox.Items.Add(CreatePresetItem("50 KB/s", 51200));
    _presetComboBox.Items.Add(CreatePresetItem("100 KB/s", 102400));
    _presetComboBox.Items.Add(CreatePresetItem("自定义 (KB/s)", null));
    _presetComboBox.SelectionChanged += PresetComboBox_SelectionChanged;

    var customLabel = new TextBlock { Text = "自定义 KB/s", Margin = new Thickness(0, 0, 0, 6) };
    _customTextBox = new System.Windows.Controls.TextBox
    {
      IsEnabled = false,
      Padding = new Thickness(10, 8, 10, 8),
      Margin = new Thickness(0, 0, 0, 16)
    };

    var buttons = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
    var saveButton = new System.Windows.Controls.Button { Content = "保存", MinWidth = 88, Margin = new Thickness(0, 0, 8, 0), Padding = new Thickness(12, 6, 12, 6) };
    var cancelButton = new System.Windows.Controls.Button { Content = "取消", MinWidth = 88, Padding = new Thickness(12, 6, 12, 6) };
    saveButton.Click += SaveButton_Click;
    cancelButton.Click += (_, _) => DialogResult = false;
    buttons.Children.Add(saveButton);
    buttons.Children.Add(cancelButton);

    Grid.SetRow(macLabel, 0);
    Grid.SetRow(macText, 1);
    Grid.SetRow(presetLabel, 2);
    Grid.SetRow(_presetComboBox, 3);
    Grid.SetRow(customLabel, 4);
    Grid.SetRow(_customTextBox, 5);

    root.Children.Add(macLabel);
    root.Children.Add(macText);
    root.Children.Add(presetLabel);
    root.Children.Add(_presetComboBox);
    root.Children.Add(customLabel);
    root.Children.Add(_customTextBox);

    var buttonRow = new Grid();
    buttonRow.Children.Add(buttons);
    Grid.SetRow(buttonRow, 6);
    root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    root.Children.Add(buttonRow);

    Content = root;
    InitializePreset(currentLimitBytesPerSecond);
  }

  private static System.Windows.Controls.ComboBoxItem CreatePresetItem(string text, long? bytesPerSecond)
  {
    var item = new System.Windows.Controls.ComboBoxItem { Content = text };
    if (bytesPerSecond is > 0)
      item.Tag = bytesPerSecond.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
    return item;
  }

  private void InitializePreset(long? currentLimitBytesPerSecond)
  {
    if (currentLimitBytesPerSecond is not > 0)
    {
      _presetComboBox.SelectedIndex = 0;
      return;
    }

    foreach (System.Windows.Controls.ComboBoxItem item in _presetComboBox.Items)
    {
      if (item.Tag is string tagText
          && long.TryParse(tagText, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var presetBytes)
          && presetBytes == currentLimitBytesPerSecond.Value)
      {
        _presetComboBox.SelectedItem = item;
        return;
      }
    }

    _presetComboBox.SelectedIndex = _presetComboBox.Items.Count - 1;
    _customTextBox.IsEnabled = true;
    var kbps = currentLimitBytesPerSecond.Value / 1024d;
    _customTextBox.Text = kbps.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture);
  }

  private void PresetComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
    var selected = _presetComboBox.SelectedItem as System.Windows.Controls.ComboBoxItem;
    var isCustom = selected?.Content?.ToString() == "自定义 (KB/s)";
    _customTextBox.IsEnabled = isCustom;
    if (!isCustom)
      _customTextBox.Text = string.Empty;
  }

  private void SaveButton_Click(object sender, RoutedEventArgs e)
  {
    var selected = _presetComboBox.SelectedItem as System.Windows.Controls.ComboBoxItem;
    if (selected == null)
      return;

    if (selected.Content?.ToString() == "不限制")
    {
      MaxBytesPerSecond = null;
      DialogResult = true;
      return;
    }

    if (selected.Tag is string tag
        && long.TryParse(tag, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out var presetBytes))
    {
      MaxBytesPerSecond = presetBytes;
      DialogResult = true;
      return;
    }

    if (selected.Content?.ToString() != "自定义 (KB/s)")
      return;

    var input = _customTextBox.Text.Trim();
    if (input.EndsWith("K", StringComparison.OrdinalIgnoreCase)
        || input.EndsWith("KB", StringComparison.OrdinalIgnoreCase)
        || input.EndsWith("KB/S", StringComparison.OrdinalIgnoreCase))
    {
      input = input
          .Replace("KB/S", string.Empty, StringComparison.OrdinalIgnoreCase)
          .Replace("KB", string.Empty, StringComparison.OrdinalIgnoreCase)
          .Replace("K", string.Empty, StringComparison.OrdinalIgnoreCase)
          .Trim();
    }

    if (!double.TryParse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var kbps)
        && !double.TryParse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.CurrentCulture, out kbps))
    {
      System.Windows.MessageBox.Show(this, "请输入有效的 KB/s 数值,例如 10。", "设置限速", MessageBoxButton.OK, MessageBoxImage.Warning);
      return;
    }

    if (kbps <= 0)
    {
      MaxBytesPerSecond = null;
      DialogResult = true;
      return;
    }

    MaxBytesPerSecond = Math.Max(1, (long)(kbps * 1024d));
    DialogResult = true;
  }
}

/// <summary>主窗口:热点配置、设备列表、策略操作与状态刷新。</summary>
public partial class Main : Window
{
  private readonly WiFiRouterService _routerService = new();
  private readonly DispatcherTimer _statusTimer;
  private readonly TrayIconService _trayIcon;
  private bool _isBusy;
  private bool _isExiting;
  private bool _hostedNetworkSupported;
  private bool _hasWiFiAdapter;
  private bool _mobileHotspotAvailable;
  private bool _isPasswordVisible;
  private ConnectedClient? _contextMenuClient;

  public Main()
  {
    InitializeComponent();

    _statusTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
    _statusTimer.Tick += async (_, _) => await RefreshStatusAsync(showErrors: false);

    _trayIcon = new TrayIconService("WiFiShared", ShowFromTray, ExitFromTrayAsync);

    Loaded += async (_, _) =>
    {
      await InitializeAsync();
      _statusTimer.Start();
    };

    Closing += OnClosing;
    Closed += (_, _) => _statusTimer.Stop();
  }

  /// <summary>关闭窗口时最小化到托盘,而非直接退出。</summary>
  private void OnClosing(object? sender, System.ComponentModel.CancelEventArgs e)
  {
    if (_isExiting)
      return;

    e.Cancel = true;
    HideToTray();
  }

  private void HideToTray()
  {
    Hide();
    ShowInTaskbar = false;
  }

  private void ShowFromTray()
  {
    Show();
    ShowInTaskbar = true;
    WindowState = WindowState.Normal;
    Activate();
  }

  private async Task ExitFromTrayAsync()
  {
    if (_isExiting)
      return;

    _isExiting = true;
    _statusTimer.Stop();

    try
    {
      var status = await _routerService.GetStatusAsync();
      if (status.IsRunning)
        await _routerService.StopRouterAsync();
    }
    catch
    {
      // 退出时忽略清理过程中的错误。
    }

    _trayIcon.Dispose();
    System.Windows.Application.Current.Shutdown();
  }

  private async Task InitializeAsync()
  {
    await RefreshAdaptersAsync();

    var status = await _routerService.GetStatusAsync();
    SsidTextBox.Text = string.IsNullOrWhiteSpace(status.Ssid) ? "WiFiShared" : status.Ssid;
    if (PasswordBox.Password.Length == 0)
      PasswordBox.Password = "WiFiShared123";

    UpdateStatusUi(status);

    _hostedNetworkSupported = await _routerService.IsSupportedAsync();
    _mobileHotspotAvailable = new MobileHotspotService().IsAvailable();
    var wifiAdapter = await _routerService.NetworkDiscovery.FindWiFiAdapterAsync();
    _hasWiFiAdapter = wifiAdapter != null;
    UpdateSupportUi();
    UpdateStartButtonState(status.IsRunning);
  }

  private async Task RefreshAdaptersAsync()
  {
    var adapters = _routerService.NetworkDiscovery.GetAdapters();
    AdaptersListView.ItemsSource = adapters;

    var upstreamCandidates = adapters.Where(a => !a.IsVirtual && !a.IsWiFi).ToList();
    UpstreamComboBox.ItemsSource = upstreamCandidates;

    var defaultUpstream = _routerService.NetworkDiscovery.FindUpstreamAdapter();
    if (defaultUpstream != null)
      UpstreamComboBox.SelectedItem = upstreamCandidates
          .FirstOrDefault(a => string.Equals(a.Name, defaultUpstream.Name, StringComparison.OrdinalIgnoreCase));

    if (UpstreamComboBox.SelectedItem == null && upstreamCandidates.Count > 0)
      UpstreamComboBox.SelectedIndex = 0;

    var wifiAdapter = await _routerService.NetworkDiscovery.FindWiFiAdapterAsync();
    _hasWiFiAdapter = wifiAdapter != null;
    WiFiAdapterTextBox.Text = wifiAdapter?.DisplayName ?? "未检测到 USB WiFi 网卡";
  }

  private async Task RefreshStatusAsync(bool showErrors)
  {
    if (_isBusy)
      return;

    try
    {
      var status = await _routerService.GetStatusAsync();
      UpdateStatusUi(status);
    }
    catch (Exception ex) when (!showErrors)
    {
      StatusTextBlock.Text = "状态读取失败";
      ClientsTextBlock.Text = ex.Message;
    }
  }

  private void UpdateStatusUi(HotspotStatus status)
  {
    StatusTextBlock.Text = status.IsRunning
        ? $"热点运行中:{status.Ssid}"
        : status.IsConfigured
            ? $"热点已配置但未启动:{status.Ssid}"
            : "热点未启动";

    ClientsTextBlock.Text = status.IsRunning
        ? $"已连接设备:{status.ConnectedClients} / {status.MaxClients}"
        : status.IsConfigured
            ? "热点未真正广播,请点击「停止共享」后重新启动。"
            : string.Empty;

    ClientsListView.ItemsSource = status.Clients;
    UpdateStartButtonState(status.IsRunning);
    StopButton.IsEnabled = status.IsRunning && !_isBusy;
  }

  private void TogglePasswordVisibilityButton_Click(object sender, RoutedEventArgs e)
  {
    _isPasswordVisible = !_isPasswordVisible;

    if (_isPasswordVisible)
    {
      PasswordTextBox.Text = PasswordBox.Password;
      PasswordBox.Visibility = Visibility.Collapsed;
      PasswordTextBox.Visibility = Visibility.Visible;
      TogglePasswordVisibilityButton.Content = "隐藏";
      TogglePasswordVisibilityButton.ToolTip = "隐藏密码";
      PasswordTextBox.Focus();
      PasswordTextBox.CaretIndex = PasswordTextBox.Text.Length;
    }
    else
    {
      PasswordBox.Password = PasswordTextBox.Text;
      PasswordTextBox.Visibility = Visibility.Collapsed;
      PasswordBox.Visibility = Visibility.Visible;
      TogglePasswordVisibilityButton.Content = "显示";
      TogglePasswordVisibilityButton.ToolTip = "显示密码";
      PasswordBox.Focus();
    }
  }

  private string GetWifiPassword() =>
      _isPasswordVisible ? PasswordTextBox.Text : PasswordBox.Password;

  private void ClientsListView_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
  {
    if (FindAncestor<System.Windows.Controls.ListViewItem>(e.OriginalSource as DependencyObject) is not System.Windows.Controls.ListViewItem item)
      return;

    item.IsSelected = true;
    item.Focus();
    _contextMenuClient = item.Content as ConnectedClient;
  }

  private void ClientsListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
  {
    if (GetSelectedContextClient() is { } client)
      _ = EditSelectedClientRemarkAsync(client);
  }

  private void EditClientRemarkMenuItem_Click(object sender, RoutedEventArgs e)
  {
    if (GetSelectedContextClient() is { } client)
      _ = EditSelectedClientRemarkAsync(client);
  }

  private void ClientsContextMenu_Opened(object sender, RoutedEventArgs e)
  {
    if (GetSelectedContextClient() is not ConnectedClient client)
    {
      BlockClientMenuItem.IsEnabled = false;
      ClearClientBandwidthMenuItem.IsEnabled = false;
      return;
    }

    _contextMenuClient = client;
    BlockClientMenuItem.IsEnabled = true;
    BlockClientMenuItem.Header = client.IsBlocked ? "取消拉黑" : "拉黑设备";
    ClearClientBandwidthMenuItem.IsEnabled = client.HasBandwidthLimit;
  }

  private void BlockClientMenuItem_Click(object sender, RoutedEventArgs e)
  {
    if (GetSelectedContextClient() is { } client)
      _ = ToggleSelectedClientBlockAsync(client);
  }

  private void SetClientBandwidthMenuItem_Click(object sender, RoutedEventArgs e)
  {
    if (GetSelectedContextClient() is { } client)
      _ = SetSelectedClientBandwidthAsync(client);
  }

  private void ClearClientBandwidthMenuItem_Click(object sender, RoutedEventArgs e)
  {
    if (GetSelectedContextClient() is not ConnectedClient client)
      return;

    _ = RunClientPolicyOperationAsync(async () =>
    {
      await _routerService.SetClientBandwidthLimitAsync(client.MacAddress, null);
      MessageTextBlock.Text = "已取消设备限速。";
    });
  }

  private ConnectedClient? GetSelectedContextClient() =>
      ClientsListView.SelectedItem as ConnectedClient ?? _contextMenuClient;

  private static T? FindAncestor<T>(DependencyObject? current) where T : DependencyObject
  {
    while (current != null)
    {
      if (current is T match)
        return match;

      current = VisualTreeHelper.GetParent(current);
    }

    return null;
  }

  private async Task ToggleSelectedClientBlockAsync(ConnectedClient client)
  {
    var action = client.IsBlocked ? "取消拉黑" : "拉黑";
    var deviceName = string.IsNullOrWhiteSpace(client.Remark) ? client.MacAddress : client.Remark;
    var confirm = System.Windows.MessageBox.Show(
        this,
        client.IsBlocked
            ? $"确定取消对「{deviceName}」的拉黑吗?"
            : $"确定拉黑「{deviceName}」吗?\n拉黑后该设备将无法通过热点访问网络。",
        action,
        MessageBoxButton.YesNo,
        MessageBoxImage.Question);

    if (confirm != MessageBoxResult.Yes)
      return;

    await RunClientPolicyOperationAsync(async () =>
    {
      await _routerService.SetClientBlockedAsync(client.MacAddress, !client.IsBlocked);
      MessageTextBlock.Text = client.IsBlocked
          ? "已取消拉黑。"
          : "已拉黑该设备,其网络流量将被拦截。";
    });
  }

  private async Task SetSelectedClientBandwidthAsync(ConnectedClient client)
  {
    _statusTimer.Stop();

    try
    {
      var dialog = new EditClientBandwidthDialog(client.MacAddress, client.MaxBytesPerSecond) { Owner = this };
      if (dialog.ShowDialog() != true)
        return;

      await _routerService.SetClientBandwidthLimitAsync(client.MacAddress, dialog.MaxBytesPerSecond);
      var status = await _routerService.GetStatusAsync();
      UpdateStatusUi(status);
      MessageTextBlock.Text = dialog.MaxBytesPerSecond is > 0
          ? "已更新设备限速。"
          : "已取消设备限速。";
    }
    catch (Exception ex)
    {
      MessageTextBlock.Text = ExceptionHelper.GetMessage(ex);
    }
    finally
    {
      _statusTimer.Start();
    }
  }

  private async Task RunClientPolicyOperationAsync(Func<Task> action)
  {
    _statusTimer.Stop();

    try
    {
      await action();
      var status = await _routerService.GetStatusAsync();
      UpdateStatusUi(status);
    }
    catch (Exception ex)
    {
      MessageTextBlock.Text = ExceptionHelper.GetMessage(ex);
    }
    finally
    {
      _statusTimer.Start();
    }
  }

  private async Task EditSelectedClientRemarkAsync(ConnectedClient client)
  {
    _statusTimer.Stop();

    try
    {
      var currentRemark = _routerService.RemarkStore.GetRemark(client.MacAddress) ?? client.Remark;
      var dialog = new EditClientRemarkDialog(client.MacAddress, currentRemark) { Owner = this };
      if (dialog.ShowDialog() != true)
        return;

      _routerService.RemarkStore.SetRemark(client.MacAddress, dialog.Remark);

      var status = await _routerService.GetStatusAsync();
      UpdateStatusUi(status);
    }
    finally
    {
      _statusTimer.Start();
    }
  }

  private void UpdateSupportUi()
  {
    if (_mobileHotspotAvailable)
    {
      SupportTextBlock.Text = "使用 Windows 移动热点共享网络(含 DHCP 和 NAT)。";
      return;
    }

    SupportTextBlock.Text = _hostedNetworkSupported
        ? "当前 USB WiFi 网卡支持承载网络,可用于创建热点。"
        : _hasWiFiAdapter
            ? "未能自动确认承载网络支持,但已检测到 USB WiFi,可尝试启动。"
            : "未检测到 USB WiFi 网卡,请插入 USB WiFi 适配器。";
  }

  private void UpdateStartButtonState(bool isHotspotRunning)
  {
    StartButton.IsEnabled = (_hostedNetworkSupported || _hasWiFiAdapter) && !isHotspotRunning && !_isBusy;
  }

  private async void StartButton_Click(object sender, RoutedEventArgs e)
  {
    await RunOperationAsync(async () =>
    {
      var config = new HotspotConfig
      {
        Ssid = SsidTextBox.Text.Trim(),
        Password = GetWifiPassword()
      };

      if (string.IsNullOrWhiteSpace(config.Ssid))
        throw new InvalidOperationException("请输入热点名称。");

      var upstream = UpstreamComboBox.SelectedItem as NetworkAdapterInfo;
      await _routerService.StartRouterAsync(config, upstream?.Name);
      MessageTextBlock.Text = "WiFi 路由器已启动。其他设备可搜索热点并连接。";
      await RefreshStatusAsync(showErrors: true);
    });
  }

  private async void StopButton_Click(object sender, RoutedEventArgs e)
  {
    await RunOperationAsync(async () =>
    {
      await _routerService.StopRouterAsync();
      MessageTextBlock.Text = "WiFi 路由器已停止。";
      await RefreshStatusAsync(showErrors: true);
      await RefreshAdaptersAsync();
    });
  }

  private async void RefreshButton_Click(object sender, RoutedEventArgs e)
  {
    await RunOperationAsync(async () =>
    {
      await RefreshAdaptersAsync();
      await RefreshStatusAsync(showErrors: true);
      _hostedNetworkSupported = await _routerService.IsSupportedAsync();
      UpdateSupportUi();
      UpdateStartButtonState((await _routerService.GetStatusAsync()).IsRunning);
      MessageTextBlock.Text = string.Empty;
    }, disableButtons: false);
  }

  private async Task RunOperationAsync(Func<Task> action, bool disableButtons = true)
  {
    if (_isBusy)
      return;

    _isBusy = true;
    _statusTimer.Stop();
    MessageTextBlock.Text = string.Empty;

    if (disableButtons)
    {
      StartButton.IsEnabled = false;
      StopButton.IsEnabled = false;
    }

    try
    {
      await action();
    }
    catch (Exception ex)
    {
      MessageTextBlock.Text = ExceptionHelper.GetMessage(ex);
    }
    finally
    {
      _isBusy = false;
      _statusTimer.Start();
      await RefreshStatusAsync(showErrors: false);
    }
  }
}

/// <summary>应用程序入口(C# 不允许 Window 类 Main 与静态 Main 同名,故使用嵌套启动类)。</summary>
public static class AppEntry
{
  [STAThread]
  public static void Main()
  {
    var app = new System.Windows.Application();
    app.Run(new Main());
  }
}
main.xaml.cs

 

image

 

posted @ 2026-06-15 09:51  阿坦  阅读(21)  评论(0)    收藏  举报