"""FT8 dekoodide (ft8.py txt) ruutlokaatorid maailmakaardile: NE 110m rannajoon, punktid ruudu keskel, jooned vastuvõtja ruudust (KO29).
Kasutus: python ft8map.py out.svg captures\\ft8\\*.txt [--home KO29] [--coast data\\ne_110m_coastline.geojson] [--bbox -180,-60,180,85]"""
import argparse, glob, json, math, re

ap = argparse.ArgumentParser(); ap.add_argument("out"); ap.add_argument("txts", nargs="+"); ap.add_argument("--home", default="KO29")
ap.add_argument("--coast", default=None); ap.add_argument("--bbox", default="-180,-60,180,85"); ap.add_argument("--w", type=int, default=1000)
a = ap.parse_args()


def grid_ll(g):
    lon = (ord(g[0]) - 65) * 20 - 180 + int(g[2]) * 2 + 1; lat = (ord(g[1]) - 65) * 10 - 90 + int(g[3]) + 0.5
    return lat, lon


x0, y0, x1, y1 = [float(v) for v in a.bbox.split(",")]
W = a.w; H = int(W * (y1 - y0) / (x1 - x0) * 1.35)
def X(lon): return (lon - x0) / (x1 - x0) * W
def Y(lat): return H - (math.log(math.tan(math.pi / 4 + math.radians(lat) / 2)) - math.log(math.tan(math.pi / 4 + math.radians(y0) / 2))) / \
    (math.log(math.tan(math.pi / 4 + math.radians(y1) / 2)) - math.log(math.tan(math.pi / 4 + math.radians(y0) / 2))) * H
pts = {}; calls = {}
for pat in a.txts:
    for p in glob.glob(pat):
        band = re.search(r"ft8_(\d+)_", p); band = band.group(1) if band else "?"
        for line in open(p, encoding="utf-8"):
            m = re.search(r"\s([A-Z0-9/<>]+)\s+([A-Z0-9/<>]+)\s+([A-R]{2}\d{2})\s*$", line.strip())
            if m:
                g = m.group(3); call = m.group(2)
                pts.setdefault(g, set()).add(call); calls.setdefault(g, set()).add(band)
hl = grid_ll(a.home)
parts = [f"<svg xmlns='http://www.w3.org/2000/svg' width='{W}' height='{H}' viewBox='0 0 {W} {H}' font-family='monospace'>",
         f"<rect width='{W}' height='{H}' fill='#dfe9f0'/>"]
if a.coast:
    g = json.load(open(a.coast, encoding="utf-8"))
    for f in g["features"]:
        geom = f["geometry"]; lines = geom["coordinates"] if geom["type"] == "MultiLineString" else [geom["coordinates"]]
        for ln in lines:
            seg = [(X(p[0]), Y(p[1])) for p in ln if y0 < p[1] < y1]
            if len(seg) > 1:
                parts.append("<path d='M" + " L".join(f"{px:.1f},{py:.1f}" for px, py in seg) + "' fill='none' stroke='#6a7a5a' stroke-width='0.7'/>")
hx, hy = X(hl[1]), Y(hl[0])
for grid, cs in pts.items():
    lat, lon = grid_ll(grid); px, py = X(lon), Y(lat)
    # suurringi kaar 30 punktiga
    la1, lo1, la2, lo2 = map(math.radians, (hl[0], hl[1], lat, lon))
    d = 2 * math.asin(math.sqrt(math.sin((la2 - la1) / 2) ** 2 + math.cos(la1) * math.cos(la2) * math.sin((lo2 - lo1) / 2) ** 2))
    seg = []
    for i in range(31):
        f = i / 30
        if d < 1e-6: continue
        A = math.sin((1 - f) * d) / math.sin(d); B = math.sin(f * d) / math.sin(d)
        xx = A * math.cos(la1) * math.cos(lo1) + B * math.cos(la2) * math.cos(lo2); yy = A * math.cos(la1) * math.sin(lo1) + B * math.cos(la2) * math.sin(lo2)
        zz = A * math.sin(la1) + B * math.sin(la2); seg.append((X(math.degrees(math.atan2(yy, xx))), Y(math.degrees(math.atan2(zz, math.sqrt(xx * xx + yy * yy))))))
    if seg:
        parts.append("<path d='M" + " L".join(f"{u:.1f},{v:.1f}" for u, v in seg) + "' fill='none' stroke='#c0392b' stroke-opacity='0.5' stroke-width='0.8'/>")
    col = "#c0392b"
    parts.append(f"<circle cx='{px:.1f}' cy='{py:.1f}' r='4' fill='{col}' stroke='#fff' stroke-width='1'/>")
    label = grid + " " + "/".join(sorted(cs))[:40]
    parts.append(f"<text x='{px+6:.1f}' y='{py-4:.1f}' font-size='9' fill='#222' stroke='#fff' stroke-width='2.5' paint-order='stroke'>{label}</text>")
parts.append(f"<circle cx='{hx:.1f}' cy='{hy:.1f}' r='6' fill='#1d7a6b' stroke='#fff' stroke-width='1.5'/>")
parts.append(f"<text x='{hx+8:.1f}' y='{hy+4:.1f}' font-size='11' font-weight='bold' fill='#1d7a6b' stroke='#fff' stroke-width='3' paint-order='stroke'>{a.home} (meie)</text>")
parts.append("</svg>")
open(a.out, "w", encoding="utf-8").write("\n".join(parts))
print(f"-> {a.out}: {len(pts)} ruutu, {sum(len(v) for v in pts.values())} kutsungit ruuduga")
