import type { Agent } from '../types';

export interface FleetFilterState {
  search: string;
  tag: string;
  subnet: string;
  hashrateMin: number;
  needsAttention: boolean;
}

export const DEFAULT_FLEET_FILTERS: FleetFilterState = {
  search: '',
  tag: '',
  subnet: '',
  hashrateMin: 0,
  needsAttention: false,
};

export function agentSubnet(ip: string): string {
  const parts = (ip || '').trim().split('.');
  if (parts.length >= 3) return `${parts[0]}.${parts[1]}.${parts[2]}.x`;
  return ip || 'unknown';
}

export function agentRejectRate(agent: Agent): number {
  if (agent.shares_total <= 0) return 0;
  return (agent.shares_bad / agent.shares_total) * 100;
}

export function agentNeedsAttention(agent: Agent): boolean {
  if (agent.status !== 'online') return true;
  if (agentRejectRate(agent) >= 5 && agent.shares_total >= 10) return true;
  return false;
}

export function agentIsIdleMiner(agent: Agent): boolean {
  return agent.status === 'online' && agent.hashrate_15m < 100;
}

export function collectFleetTags(agents: Agent[]): string[] {
  const set = new Set<string>();
  for (const a of agents) {
    for (const t of a.tags || []) {
      const clean = t.trim();
      if (clean) set.add(clean);
    }
  }
  return [...set].sort((a, b) => a.localeCompare(b));
}

export function collectFleetSubnets(agents: Agent[]): string[] {
  const set = new Set<string>();
  for (const a of agents) {
    set.add(agentSubnet(a.ip));
  }
  return [...set].sort();
}

export function filterFleetAgents(agents: Agent[], filters: FleetFilterState): Agent[] {
  const q = filters.search.trim().toLowerCase();
  return agents.filter((a) => {
    if (filters.needsAttention && !agentNeedsAttention(a)) return false;
    if (filters.tag && !(a.tags || []).includes(filters.tag)) return false;
    if (filters.subnet && agentSubnet(a.ip) !== filters.subnet) return false;
    if (filters.hashrateMin > 0 && a.hashrate_15m < filters.hashrateMin) return false;
    if (q) {
      const hay = [
        a.name,
        a.ip,
        a.notes || '',
        ...(a.tags || []),
        a.id,
      ]
        .join(' ')
        .toLowerCase();
      if (!hay.includes(q)) return false;
    }
    return true;
  });
}

export function formatHashrate(h: number): string {
  if (h >= 1_000_000) return `${(h / 1_000_000).toFixed(2)} MH/s`;
  if (h >= 1_000) return `${(h / 1_000).toFixed(2)} KH/s`;
  return `${h.toFixed(0)} H/s`;
}

export function formatUptime(seconds: number): string {
  const d = Math.floor(seconds / 86400);
  const h = Math.floor((seconds % 86400) / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (d > 0) return `${d}d ${h}h`;
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m`;
}
