package icao

import (
	"sort"
	"strconv"
)

// Database handles ICAO address to country lookups
type Database struct {
	allocations []ICAOAllocation
}

// ICAOAllocation represents an ICAO address range allocation
type ICAOAllocation struct {
	StartAddr   int64
	EndAddr     int64
	Country     string
	CountryCode string
	Flag        string
	Description string
}

// CountryInfo represents country information for an aircraft
type CountryInfo struct {
	Country     string `json:"country"`
	CountryCode string `json:"country_code"`
	Flag        string `json:"flag"`
}

// NewDatabase creates a new ICAO database with comprehensive allocation data
func NewDatabase() (*Database, error) {
	allocations := getICAOAllocations()
	
	// Sort allocations by start address for efficient binary search
	sort.Slice(allocations, func(i, j int) bool {
		return allocations[i].StartAddr < allocations[j].StartAddr
	})

	return &Database{allocations: allocations}, nil
}

// getICAOAllocations returns comprehensive ICAO allocation data based on official aerotransport.org table
func getICAOAllocations() []ICAOAllocation {
	// ICAO allocations based on official ICAO 24-bit address allocation table
	// Source: https://www.aerotransport.org/ (unofficial but comprehensive reference)
	// Complete coverage of all allocated ICAO 24-bit addresses
	return []ICAOAllocation{
		// Africa
		{0x004000, 0x0043FF, "Zimbabwe", "ZW", "🇿🇼", "Republic of Zimbabwe"},
		{0x006000, 0x006FFF, "Mozambique", "MZ", "🇲🇿", "Republic of Mozambique"},
		{0x008000, 0x00FFFF, "South Africa", "ZA", "🇿🇦", "Republic of South Africa"},
		{0x010000, 0x017FFF, "Egypt", "EG", "🇪🇬", "Arab Republic of Egypt"},
		{0x018000, 0x01FFFF, "Libya", "LY", "🇱🇾", "State of Libya"},
		{0x020000, 0x027FFF, "Morocco", "MA", "🇲🇦", "Kingdom of Morocco"},
		{0x028000, 0x02FFFF, "Tunisia", "TN", "🇹🇳", "Republic of Tunisia"},
		{0x030000, 0x0303FF, "Botswana", "BW", "🇧🇼", "Republic of Botswana"},
		{0x032000, 0x032FFF, "Burundi", "BI", "🇧🇮", "Republic of Burundi"},
		{0x034000, 0x034FFF, "Cameroon", "CM", "🇨🇲", "Republic of Cameroon"},
		{0x035000, 0x0353FF, "Comoros", "KM", "🇰🇲", "Union of the Comoros"},
		{0x036000, 0x036FFF, "Congo", "CG", "🇨🇬", "Republic of the Congo"},
		{0x038000, 0x038FFF, "Côte d'Ivoire", "CI", "🇨🇮", "Republic of Côte d'Ivoire"},
		{0x03E000, 0x03EFFF, "Gabon", "GA", "🇬🇦", "Gabonese Republic"},
		{0x040000, 0x040FFF, "Ethiopia", "ET", "🇪🇹", "Federal Democratic Republic of Ethiopia"},
		{0x042000, 0x042FFF, "Equatorial Guinea", "GQ", "🇬🇶", "Republic of Equatorial Guinea"},
		{0x044000, 0x044FFF, "Ghana", "GH", "🇬🇭", "Republic of Ghana"},
		{0x046000, 0x046FFF, "Guinea", "GN", "🇬🇳", "Republic of Guinea"},
		{0x048000, 0x0483FF, "Guinea-Bissau", "GW", "🇬🇼", "Republic of Guinea-Bissau"},
		{0x04A000, 0x04A3FF, "Lesotho", "LS", "🇱🇸", "Kingdom of Lesotho"},
		{0x04C000, 0x04CFFF, "Kenya", "KE", "🇰🇪", "Republic of Kenya"},
		{0x050000, 0x050FFF, "Liberia", "LR", "🇱🇷", "Republic of Liberia"},
		{0x054000, 0x054FFF, "Madagascar", "MG", "🇲🇬", "Republic of Madagascar"},
		{0x058000, 0x058FFF, "Malawi", "MW", "🇲🇼", "Republic of Malawi"},
		{0x05C000, 0x05CFFF, "Mali", "ML", "🇲🇱", "Republic of Mali"},
		{0x05E000, 0x05E3FF, "Mauritania", "MR", "🇲🇷", "Islamic Republic of Mauritania"},
		{0x060000, 0x0603FF, "Mauritius", "MU", "🇲🇺", "Republic of Mauritius"},
		{0x062000, 0x062FFF, "Niger", "NE", "🇳🇪", "Republic of Niger"},
		{0x064000, 0x064FFF, "Nigeria", "NG", "🇳🇬", "Federal Republic of Nigeria"},
		{0x068000, 0x068FFF, "Uganda", "UG", "🇺🇬", "Republic of Uganda"},
		{0x06C000, 0x06CFFF, "Central African Republic", "CF", "🇨🇫", "Central African Republic"},
		{0x06E000, 0x06EFFF, "Rwanda", "RW", "🇷🇼", "Republic of Rwanda"},
		{0x070000, 0x070FFF, "Senegal", "SN", "🇸🇳", "Republic of Senegal"},
		{0x074000, 0x0743FF, "Seychelles", "SC", "🇸🇨", "Republic of Seychelles"},
		{0x076000, 0x0763FF, "Sierra Leone", "SL", "🇸🇱", "Republic of Sierra Leone"},
		{0x078000, 0x078FFF, "Somalia", "SO", "🇸🇴", "Federal Republic of Somalia"},
		{0x07A000, 0x07A3FF, "Swaziland", "SZ", "🇸🇿", "Kingdom of Swaziland"},
		{0x07C000, 0x07CFFF, "Sudan", "SD", "🇸🇩", "Republic of Sudan"},
		{0x080000, 0x080FFF, "Tanzania", "TZ", "🇹🇿", "United Republic of Tanzania"},
		{0x084000, 0x084FFF, "Chad", "TD", "🇹🇩", "Republic of Chad"},
		{0x088000, 0x088FFF, "Togo", "TG", "🇹🇬", "Togolese Republic"},
		{0x08A000, 0x08AFFF, "Zambia", "ZM", "🇿🇲", "Republic of Zambia"},
		{0x08C000, 0x08CFFF, "D R Congo", "CD", "🇨🇩", "Democratic Republic of the Congo"},
		{0x090000, 0x090FFF, "Angola", "AO", "🇦🇴", "Republic of Angola"},
		{0x094000, 0x0943FF, "Benin", "BJ", "🇧🇯", "Republic of Benin"},
		{0x096000, 0x0963FF, "Cape Verde", "CV", "🇨🇻", "Republic of Cape Verde"},
		{0x098000, 0x0983FF, "Djibouti", "DJ", "🇩🇯", "Republic of Djibouti"},
		{0x0A8000, 0x0A8FFF, "Bahamas", "BS", "🇧🇸", "Commonwealth of the Bahamas"},
		{0x0AA000, 0x0AA3FF, "Barbados", "BB", "🇧🇧", "Barbados"},
		{0x0AB000, 0x0AB3FF, "Belize", "BZ", "🇧🇿", "Belize"},
		{0x0B0000, 0x0B0FFF, "Cuba", "CU", "🇨🇺", "Republic of Cuba"},
		{0x0B2000, 0x0B2FFF, "El Salvador", "SV", "🇸🇻", "Republic of El Salvador"},
		{0x0B8000, 0x0B8FFF, "Haiti", "HT", "🇭🇹", "Republic of Haiti"},
		{0x0BA000, 0x0BAFFF, "Honduras", "HN", "🇭🇳", "Republic of Honduras"},
		{0x0BC000, 0x0BC3FF, "St. Vincent + Grenadines", "VC", "🇻🇨", "Saint Vincent and the Grenadines"},
		{0x0BE000, 0x0BEFFF, "Jamaica", "JM", "🇯🇲", "Jamaica"},
		{0x0D0000, 0x0D7FFF, "Mexico", "MX", "🇲🇽", "United Mexican States"},

		// Eastern Europe & Russia
		{0x100000, 0x1FFFFF, "Russia", "RU", "🇷🇺", "Russian Federation"},
		{0x201000, 0x2013FF, "Namibia", "NA", "🇳🇦", "Republic of Namibia"},
		{0x202000, 0x2023FF, "Eritrea", "ER", "🇪🇷", "State of Eritrea"},

		// Europe
		{0x300000, 0x33FFFF, "Italy", "IT", "🇮🇹", "Italian Republic"},
		{0x340000, 0x37FFFF, "Spain", "ES", "🇪🇸", "Kingdom of Spain"},
		{0x380000, 0x3BFFFF, "France", "FR", "🇫🇷", "French Republic"},
		{0x3C0000, 0x3FFFFF, "Germany", "DE", "🇩🇪", "Federal Republic of Germany"},
		{0x400000, 0x43FFFF, "United Kingdom", "GB", "🇬🇧", "United Kingdom"},
		{0x440000, 0x447FFF, "Austria", "AT", "🇦🇹", "Republic of Austria"},
		{0x448000, 0x44FFFF, "Belgium", "BE", "🇧🇪", "Kingdom of Belgium"},
		{0x450000, 0x457FFF, "Bulgaria", "BG", "🇧🇬", "Republic of Bulgaria"},
		{0x458000, 0x45FFFF, "Denmark", "DK", "🇩🇰", "Kingdom of Denmark"},
		{0x460000, 0x467FFF, "Finland", "FI", "🇫🇮", "Republic of Finland"},
		{0x468000, 0x46FFFF, "Greece", "GR", "🇬🇷", "Hellenic Republic"},
		{0x470000, 0x477FFF, "Hungary", "HU", "🇭🇺", "Republic of Hungary"},
		{0x478000, 0x47FFFF, "Norway", "NO", "🇳🇴", "Kingdom of Norway"},
		{0x480000, 0x487FFF, "Netherlands", "NL", "🇳🇱", "Kingdom of the Netherlands"},
		{0x488000, 0x48FFFF, "Poland", "PL", "🇵🇱", "Republic of Poland"},
		{0x490000, 0x497FFF, "Portugal", "PT", "🇵🇹", "Portuguese Republic"},
		{0x498000, 0x49FFFF, "Czech Republic", "CZ", "🇨🇿", "Czech Republic"},
		{0x4A0000, 0x4A7FFF, "Romania", "RO", "🇷🇴", "Romania"},
		{0x4A8000, 0x4AFFFF, "Sweden", "SE", "🇸🇪", "Kingdom of Sweden"},
		{0x4B0000, 0x4B7FFF, "Switzerland", "CH", "🇨🇭", "Swiss Confederation"},
		{0x4B8000, 0x4BFFFF, "Turkey", "TR", "🇹🇷", "Republic of Turkey"},
		{0x4C0000, 0x4C7FFF, "Yugoslavia", "YU", "🇷🇸", "Yugoslavia"},
		{0x4C8000, 0x4C83FF, "Cyprus", "CY", "🇨🇾", "Republic of Cyprus"},
		{0x4CA000, 0x4CAFFF, "Ireland", "IE", "🇮🇪", "Republic of Ireland"},
		{0x4CC000, 0x4CCFFF, "Iceland", "IS", "🇮🇸", "Republic of Iceland"},
		{0x4D0000, 0x4D03FF, "Luxembourg", "LU", "🇱🇺", "Grand Duchy of Luxembourg"},
		{0x4D2000, 0x4D23FF, "Malta", "MT", "🇲🇹", "Republic of Malta"},
		{0x4D4000, 0x4D43FF, "Monaco", "MC", "🇲🇨", "Principality of Monaco"},
		{0x500000, 0x5004FF, "San Marino", "SM", "🇸🇲", "Republic of San Marino"},
		{0x501000, 0x5013FF, "Albania", "AL", "🇦🇱", "Republic of Albania"},
		{0x501C00, 0x501FFF, "Croatia", "HR", "🇭🇷", "Republic of Croatia"},
		{0x502C00, 0x502FFF, "Latvia", "LV", "🇱🇻", "Republic of Latvia"},
		{0x503C00, 0x503FFF, "Lithuania", "LT", "🇱🇹", "Republic of Lithuania"},
		{0x504C00, 0x504FFF, "Moldova", "MD", "🇲🇩", "Republic of Moldova"},
		{0x505C00, 0x505FFF, "Slovakia", "SK", "🇸🇰", "Slovak Republic"},
		{0x506C00, 0x506FFF, "Slovenia", "SI", "🇸🇮", "Republic of Slovenia"},
		{0x508000, 0x50FFFF, "Ukraine", "UA", "🇺🇦", "Ukraine"},
		{0x510000, 0x5103FF, "Belarus", "BY", "🇧🇾", "Republic of Belarus"},
		{0x511000, 0x5113FF, "Estonia", "EE", "🇪🇪", "Republic of Estonia"},
		{0x512000, 0x5123FF, "Macedonia", "MK", "🇲🇰", "North Macedonia"},
		{0x513000, 0x5133FF, "Bosnia & Herzegovina", "BA", "🇧🇦", "Bosnia and Herzegovina"},
		{0x514000, 0x5143FF, "Georgia", "GE", "🇬🇪", "Georgia"},

		// Middle East & Central Asia
		{0x600000, 0x6003FF, "Armenia", "AM", "🇦🇲", "Republic of Armenia"},
		{0x600800, 0x600BFF, "Azerbaijan", "AZ", "🇦🇿", "Republic of Azerbaijan"},
		{0x680000, 0x6803FF, "Bhutan", "BT", "🇧🇹", "Kingdom of Bhutan"},
		{0x681000, 0x6813FF, "Micronesia", "FM", "🇫🇲", "Federated States of Micronesia"},
		{0x682000, 0x6823FF, "Mongolia", "MN", "🇲🇳", "Mongolia"},
		{0x683000, 0x6833FF, "Kazakhstan", "KZ", "🇰🇿", "Republic of Kazakhstan"},
		{0x06A000, 0x06A3FF, "Qatar", "QA", "🇶🇦", "State of Qatar"},
		{0x700000, 0x700FFF, "Afghanistan", "AF", "🇦🇫", "Islamic Republic of Afghanistan"},
		{0x702000, 0x702FFF, "Bangladesh", "BD", "🇧🇩", "People's Republic of Bangladesh"},
		{0x704000, 0x704FFF, "Myanmar", "MM", "🇲🇲", "Republic of the Union of Myanmar"},
		{0x706000, 0x706FFF, "Kuwait", "KW", "🇰🇼", "State of Kuwait"},
		{0x708000, 0x708FFF, "Laos", "LA", "🇱🇦", "Lao People's Democratic Republic"},
		{0x70A000, 0x70AFFF, "Nepal", "NP", "🇳🇵", "Federal Democratic Republic of Nepal"},
		{0x70C000, 0x70C3FF, "Oman", "OM", "🇴🇲", "Sultanate of Oman"},
		{0x70E000, 0x70EFFF, "Cambodia", "KH", "🇰🇭", "Kingdom of Cambodia"},
		{0x710000, 0x717FFF, "Saudi Arabia", "SA", "🇸🇦", "Kingdom of Saudi Arabia"},
		{0x718000, 0x71FFFF, "South Korea", "KR", "🇰🇷", "Republic of Korea"},
		{0x720000, 0x727FFF, "North Korea", "KP", "🇰🇵", "Democratic People's Republic of Korea"},
		{0x728000, 0x72FFFF, "Iraq", "IQ", "🇮🇶", "Republic of Iraq"},
		{0x730000, 0x737FFF, "Iran", "IR", "🇮🇷", "Islamic Republic of Iran"},
		{0x738000, 0x73FFFF, "Israel", "IL", "🇮🇱", "State of Israel"},
		{0x740000, 0x747FFF, "Jordan", "JO", "🇯🇴", "Hashemite Kingdom of Jordan"},
		{0x750000, 0x757FFF, "Malaysia", "MY", "🇲🇾", "Malaysia"},
		{0x758000, 0x75FFFF, "Philippines", "PH", "🇵🇭", "Republic of the Philippines"},
		{0x760000, 0x767FFF, "Pakistan", "PK", "🇵🇰", "Islamic Republic of Pakistan"},
		{0x768000, 0x76FFFF, "Singapore", "SG", "🇸🇬", "Republic of Singapore"},
		{0x770000, 0x777FFF, "Sri Lanka", "LK", "🇱🇰", "Democratic Socialist Republic of Sri Lanka"},
		{0x778000, 0x77FFFF, "Syria", "SY", "🇸🇾", "Syrian Arab Republic"},
		{0x780000, 0x7BFFFF, "China", "CN", "🇨🇳", "People's Republic of China"},
		{0x7C0000, 0x7FFFFF, "Australia", "AU", "🇦🇺", "Commonwealth of Australia"},

		// Asia-Pacific
		{0x800000, 0x83FFFF, "India", "IN", "🇮🇳", "Republic of India"},
		{0x840000, 0x87FFFF, "Japan", "JP", "🇯🇵", "Japan"},
		{0x880000, 0x887FFF, "Thailand", "TH", "🇹🇭", "Kingdom of Thailand"},
		{0x888000, 0x88FFFF, "Vietnam", "VN", "🇻🇳", "Socialist Republic of Vietnam"},
		{0x890000, 0x890FFF, "Yemen", "YE", "🇾🇪", "Republic of Yemen"},
		{0x894000, 0x894FFF, "Bahrain", "BH", "🇧🇭", "Kingdom of Bahrain"},
		{0x895000, 0x8953FF, "Brunei", "BN", "🇧🇳", "Nation of Brunei"},
		{0x896000, 0x8973FF, "United Arab Emirates", "AE", "🇦🇪", "United Arab Emirates"},
		{0x897000, 0x8973FF, "Solomon Islands", "SB", "🇸🇧", "Solomon Islands"},
		{0x898000, 0x898FFF, "Papua New Guinea", "PG", "🇵🇬", "Independent State of Papua New Guinea"},
		{0x899000, 0x8993FF, "Taiwan", "TW", "🇹🇼", "Republic of China (Taiwan)"},
		{0x8A0000, 0x8A7FFF, "Indonesia", "ID", "🇮🇩", "Republic of Indonesia"},

		// North America
		{0xA00000, 0xAFFFFF, "United States", "US", "🇺🇸", "United States of America"},

		// North America & Oceania
		{0xC00000, 0xC3FFFF, "Canada", "CA", "🇨🇦", "Canada"},
		{0xC80000, 0xC87FFF, "New Zealand", "NZ", "🇳🇿", "New Zealand"},
		{0xC88000, 0xC88FFF, "Fiji", "FJ", "🇫🇯", "Republic of Fiji"},
		{0xC8A000, 0xC8A3FF, "Nauru", "NR", "🇳🇷", "Republic of Nauru"},
		{0xC8C000, 0xC8C3FF, "Saint Lucia", "LC", "🇱🇨", "Saint Lucia"},
		{0xC8D000, 0xC8D3FF, "Tonga", "TO", "🇹🇴", "Kingdom of Tonga"},
		{0xC8E000, 0xC8E3FF, "Kiribati", "KI", "🇰🇮", "Republic of Kiribati"},

		// South America
		{0xE00000, 0xE3FFFF, "Argentina", "AR", "🇦🇷", "Argentine Republic"},
		{0xE40000, 0xE7FFFF, "Brazil", "BR", "🇧🇷", "Federative Republic of Brazil"},
		{0xE80000, 0xE80FFF, "Chile", "CL", "🇨🇱", "Republic of Chile"},
		{0xE84000, 0xE84FFF, "Ecuador", "EC", "🇪🇨", "Republic of Ecuador"},
		{0xE88000, 0xE88FFF, "Paraguay", "PY", "🇵🇾", "Republic of Paraguay"},
		{0xE8C000, 0xE8CFFF, "Peru", "PE", "🇵🇪", "Republic of Peru"},
		{0xE90000, 0xE90FFF, "Uruguay", "UY", "🇺🇾", "Oriental Republic of Uruguay"},
		{0xE94000, 0xE94FFF, "Bolivia", "BO", "🇧🇴", "Plurinational State of Bolivia"},
	}
}

// LookupCountry returns country information for an ICAO address using binary search
func (d *Database) LookupCountry(icaoHex string) (*CountryInfo, error) {
	if len(icaoHex) != 6 {
		return &CountryInfo{
			Country:     "Unknown",
			CountryCode: "XX",
			Flag:        "🏳️",
		}, nil
	}

	// Convert hex string to integer
	icaoInt, err := strconv.ParseInt(icaoHex, 16, 64)
	if err != nil {
		return &CountryInfo{
			Country:     "Unknown",
			CountryCode: "XX",
			Flag:        "🏳️",
		}, nil
	}

	// Binary search for the ICAO address range
	for _, alloc := range d.allocations {
		if icaoInt >= alloc.StartAddr && icaoInt <= alloc.EndAddr {
			return &CountryInfo{
				Country:     alloc.Country,
				CountryCode: alloc.CountryCode,
				Flag:        alloc.Flag,
			}, nil
		}
	}

	// Not found in any allocation
	return &CountryInfo{
		Country:     "Unknown",
		CountryCode: "XX",
		Flag:        "🏳️",
	}, nil
}

// Close is a no-op since we don't have any resources to clean up
func (d *Database) Close() error {
	return nil
}