import pymysql
import os

OUTPUT_DIR = "report"
os.makedirs(OUTPUT_DIR, exist_ok=True)

conn = pymysql.connect(
    host="localhost",
    user="root",
    password="2chi9ks2",
    database="pbf_analysis",
    charset="utf8mb4"
)

cur = conn.cursor()

def write_file(name, rows):

    path = os.path.join(OUTPUT_DIR, name)

    with open(path,"w",encoding="utf8") as f:

        for r in rows:
            f.write("\t".join([str(x) for x in r])+"\n")

    print("write:",path)


print("Layer summary...")

cur.execute("""
SELECT vt_layer, COUNT(*) 
FROM features
GROUP BY vt_layer
ORDER BY COUNT(*) DESC
""")

write_file("layer_summary.txt",cur.fetchall())


print("Geometry summary...")

cur.execute("""
SELECT vt_layer, geom_type, COUNT(*)
FROM features
GROUP BY vt_layer, geom_type
ORDER BY vt_layer
""")

write_file("geometry_summary.txt",cur.fetchall())


print("Property keys...")

cur.execute("""
SELECT k, COUNT(*)
FROM properties
GROUP BY k
ORDER BY COUNT(*) DESC
""")

write_file("property_keys.txt",cur.fetchall())


print("Layer properties...")

cur.execute("""
SELECT f.vt_layer, p.k, COUNT(*)
FROM properties p
JOIN features f ON p.feature_id=f.id
GROUP BY f.vt_layer,p.k
ORDER BY f.vt_layer
""")

write_file("layer_properties.txt",cur.fetchall())


print("Classification distribution...")

cur.execute("""
SELECT v, COUNT(*)
FROM properties
WHERE k='分類番号'
GROUP BY v
ORDER BY COUNT(*) DESC
""")

write_file("classification_distribution.txt",cur.fetchall())


print("Tile density...")

cur.execute("""
SELECT z,x,y,COUNT(*)
FROM features
GROUP BY z,x,y
ORDER BY COUNT(*) DESC
LIMIT 100
""")

write_file("tile_density.txt",cur.fetchall())


print("done.")