#!/usr/bin/env python3
"""Generate proposed SEO (title, meta desc, H1, keywords, alt rule) for every page/category/product.
Pairs each with the EXISTING scraped meta for side-by-side review. Nothing is applied to the live site."""
import json, html, re

def c(s): return html.unescape(re.sub('<[^>]+>','',s or '')).strip()

scrape = {r['url']: r for r in json.load(open('seo_scrape.json'))}
cats   = json.load(open('categories.json'))
pages  = json.load(open('pages.json'))
prods  = json.load(open('products1.json')) + json.load(open('products2.json'))

BRAND = "Technosys"
def ex(url, field):
    r = scrape.get(url, {})
    if field=='title': return c(r.get('title',''))
    if field=='desc':  return c(r.get('desc',''))
    if field=='h1':    return r.get('h1_count', '?')
    return ''

proposals = []  # each: scope,name,url,ex_title,ex_desc,ex_h1, pr_title,pr_desc,pr_h1, primary_kw, secondary_kw

# ---------- HAND-AUTHORED: HOMEPAGE ----------
proposals.append({
  'scope':'Homepage','name':'Homepage','url':'https://technosysequipment.com/',
  'pr_title':'Material Handling Equipment Manufacturer India | Technosys',
  'pr_desc':'India’s leading manufacturer of pallet trucks, forklifts, stackers & AGVs. ISO 9001 certified. Custom-built, export worldwide. Get a free quote today!',
  'pr_h1':'Material Handling Equipment Manufacturer in India',
  'primary_kw':'material handling equipment manufacturer India',
  'secondary_kw':'pallet truck, forklift, stacker, AGV, warehouse equipment, Pune',
})

# ---------- HAND-AUTHORED: STATIC PAGES ----------
static = [
 ('About','https://technosysequipment.com/about-technosys/',
  'Material Handling Equipment Manufacturer Since 2014 | Technosys',
  'Technosys Equipments — ISO 9001:2015 certified manufacturer & global exporter of 150+ material handling products from Pune, India. Discover our story.',
  'About Technosys Equipments — Your Material Movement Partner',
  'about technosys equipments','material handling manufacturer Pune, ISO certified, exporter India'),
 ('Contact','https://technosysequipment.com/contact-technosys/',
  'Contact Technosys | Material Handling Equipment Enquiry India',
  'Contact Technosys Equipments, Pune. Call +91 8805 888 333 for material handling equipment quotes, custom builds & bulk export orders. Fast response.',
  'Contact Technosys Equipments — Get a Free Quote',
  'contact technosys','material handling equipment enquiry, get a quote, Pune'),
 ('AGV','https://technosysequipment.com/about-agv/',
  'AGV Manufacturer India | Automated Guided Vehicles | Technosys',
  'Custom Automated Guided Vehicles (AGV) for warehouses, manufacturing & logistics. Industry 4.0 material movement from India’s AGV experts. Enquire now.',
  'Automated Guided Vehicle (AGV) Manufacturer in India',
  'AGV manufacturer India','automated guided vehicle, warehouse automation, Industry 4.0'),
 ('Custom Solutions','https://technosysequipment.com/technosys-custom-solutions/',
  'Custom Material Handling Solutions India | Technosys',
  'Bespoke material handling equipment engineered to your load, space & industry. Custom pallet trucks, stackers & trolleys built in Pune, India. Get a quote.',
  'Custom Material Handling Solutions — Built for Your Application',
  'custom material handling solutions India','customised equipment, bespoke material handling, OEM'),
 ('Careers','https://technosysequipment.com/careers/',
  'Careers at Technosys | Material Handling Jobs in Pune',
  'Join Technosys Equipments, Pune. Explore engineering, sales & production careers with India’s growing material handling equipment manufacturer. Apply now.',
  'Careers at Technosys Equipments',
  'technosys careers','material handling jobs Pune, manufacturing careers India'),
]
for name,url,t,d,h1,pk,sk in static:
    proposals.append({'scope':'Static Page','name':name,'url':url,'pr_title':t,'pr_desc':d,'pr_h1':h1,'primary_kw':pk,'secondary_kw':sk})

# ---------- HAND-AUTHORED: CATEGORY PAGES (the money pages) ----------
cat_seo = {
 'drum-handling-equipments':('Drum Handling Equipment Manufacturer India | Technosys',
   'Drum trolleys, tilters, stackers & lifters for safe drum movement. Capacities up to 350kg+. ISO certified manufacturer in Pune, India. Get a free quote.',
   'Drum Handling Equipment Manufacturer in India','drum handling equipment manufacturer','drum trolley, drum tilter, drum lifter, drum stacker India'),
 'loading-equipments':('Dock Leveler & Loading Equipment Manufacturer India | Technosys',
   'Dock levelers, loading ramps & scissor lifts for warehouses & factories. Heavy-duty loading equipment built in Pune, India. Request pricing today.',
   'Loading Equipment & Dock Leveler Manufacturer in India','loading equipment manufacturer India','dock leveler, loading ramp, scissor lift, dock equipment'),
 'stacker':('Electric & Manual Stacker Manufacturer in India | Technosys',
   'Electric, semi-electric & manual stackers for warehouse stacking. Lift heights & capacities to suit any facility. Made in Pune, India. Get a quote.',
   'Stacker Machine Manufacturer in India','stacker manufacturer India','electric stacker, manual stacker, pallet stacker, warehouse stacker'),
 'special-equipments':('Special Material Handling Equipment Manufacturer | Technosys',
   'Specialised material handling equipment for unique industrial needs. Purpose-built machines engineered in Pune, India. Tell us your application — get a quote.',
   'Special Purpose Material Handling Equipment','special material handling equipment','special purpose equipment, industrial handling machines'),
 'reel-handling-equipments':('Reel Handling Equipment Manufacturer India | Technosys',
   'Reel trolleys, reel lifters & paper roll handling equipment for printing, packaging & textile industries. Built in Pune, India. Request a quote.',
   'Reel Handling Equipment Manufacturer in India','reel handling equipment manufacturer','reel trolley, reel lifter, paper roll handling, coil handling'),
 'storage-solution':('Industrial Storage & Pallet Racking Solutions India | Technosys',
   'Pallet racking, shelving & metal pallets for warehouse storage optimisation. Custom storage solutions from Pune, India. Maximise space — get a quote.',
   'Industrial Storage Solutions & Pallet Racking','industrial storage solutions India','pallet racking, warehouse shelving, metal pallets, storage systems'),
 'battery-pallet-truck':('Battery Pallet Truck Manufacturer India | Electric Pallet Jack | Technosys',
   'Battery-operated electric pallet trucks up to 20,000kg. Reliable, low-maintenance, fast delivery across India & worldwide. ISO certified. Get a quote.',
   'Battery Operated Pallet Truck Manufacturer in India','battery pallet truck manufacturer India','electric pallet truck, electric pallet jack, BOPT'),
 'customised-equipments':('Customised Material Handling Equipment India | Technosys',
   'Material handling equipment customised to your exact load, aisle & process. Engineered & built in Pune, India. Share your spec — get a custom quote.',
   'Customised Material Handling Equipment','customised material handling equipment','custom pallet truck, custom stacker, bespoke equipment'),
 'attachments':('Forklift Attachments Manufacturer India | Technosys',
   'Forklift attachments — clamps, rotators, booms & fork extensions for every load type. Manufactured in Pune, India. Boost forklift versatility. Get a quote.',
   'Forklift Attachments Manufacturer in India','forklift attachments manufacturer India','forklift clamp, rotator, fork extension, boom attachment'),
 'hand-pallet-truck':('Hand Pallet Truck Manufacturer India | Hydraulic Pallet Jack | Technosys',
   'Hydraulic & high-lift hand pallet trucks up to 2500kg. Durable, low-maintenance, CE-grade. Trusted manufacturer in Pune, India. Get a free quote.',
   'Hand Pallet Truck Manufacturer in India','hand pallet truck manufacturer India','hydraulic hand pallet truck, manual pallet jack, high lift pallet truck'),
 'towing-equipments':('Towing Equipment & Tow Trucks Manufacturer India | Technosys',
   'Industrial tow tractors, power pushers & towing equipment for in-plant transport. Built in Pune, India. Move heavy loads easily — request a quote.',
   'Towing Equipment Manufacturer in India','towing equipment manufacturer India','tow tractor, power pusher, towing tug, in-plant towing'),
 'platform-truck':('Platform Truck & Trolley Manufacturer India | Technosys',
   'Heavy-duty platform trucks & trolleys for material transport across factories & warehouses. Built tough in Pune, India. Request pricing today.',
   'Platform Truck Manufacturer in India','platform truck manufacturer India','platform trolley, material transport trolley, industrial cart'),
 'shop-floor-crane':('Shop Floor Crane & Floor Crane Manufacturer India | Technosys',
   'Hydraulic shop floor cranes & engine cranes for lifting heavy loads on the factory floor. Made in Pune, India. Lift safely — get a quote.',
   'Shop Floor Crane Manufacturer in India','shop floor crane manufacturer India','floor crane, hydraulic crane, engine crane, workshop crane'),
 'narrow-aisle-truck':('Narrow Aisle Truck Manufacturer India | VNA Truck | Technosys',
   'Narrow aisle (VNA) trucks for high-density warehouse storage. Maximise aisle space & throughput. Manufactured in Pune, India. Request a quote.',
   'Narrow Aisle Truck Manufacturer in India','narrow aisle truck manufacturer India','VNA truck, very narrow aisle, high density storage truck'),
 'die-handling-truck':('Die Handling Truck Manufacturer India | Technosys',
   'Die handling trucks & die loaders for press shops & tool rooms. Safe, ergonomic die movement built in Pune, India. Get a free quote.',
   'Die Handling Truck Manufacturer in India','die handling truck manufacturer India','die loader, die cart, press die handling, tool room equipment'),
 'forklifts':('Electric Forklift Manufacturer India | 3 & 4 Wheel | Technosys',
   '3-wheel & 4-wheel electric forklifts and compact forklifts for warehouses & factories. ISO certified, built in Pune, India. Get a forklift quote.',
   'Electric Forklift Manufacturer in India','electric forklift manufacturer India','3 wheel forklift, 4 wheel forklift, compact electric forklift'),
 'order-picker-work-platform':('Order Picker & Work Platform Manufacturer India | Technosys',
   'Order pickers & elevating work platforms for fast, safe picking at height. Built in Pune, India. Improve picking productivity — request a quote.',
   'Order Picker & Work Platform Manufacturer in India','order picker manufacturer India','order picker machine, work platform, picking truck'),
 'platform-trolley':('Platform Trolley Manufacturer India | Technosys',
   'Durable platform trolleys for safe in-plant material transport. Multiple sizes & capacities, built in Pune, India. Request pricing today.',
   'Platform Trolley Manufacturer in India','platform trolley manufacturer India','material trolley, hand trolley, industrial platform trolley'),
 'agv':('AGV Manufacturer India | Automated Guided Vehicles | Technosys',
   'Automated Guided Vehicles (AGV) for autonomous material movement in warehouses & factories. Custom AGV solutions from Pune, India. Enquire now.',
   'Automated Guided Vehicle (AGV) Manufacturer in India','AGV manufacturer India','automated guided vehicle, autonomous material movement, warehouse robot'),
}
cat_by_id = {ct['id']: ct for ct in cats}
for ct in sorted(cats, key=lambda i:-i['count']):
    slug = ct['slug']
    if slug=='uncategorized': continue
    url = ct['link']
    if slug in cat_seo:
        t,d,h1,pk,sk = cat_seo[slug]
    else:
        nm = html.unescape(ct['name'])
        t = f"{nm} Manufacturer in India | {BRAND}"[:60]
        d = f"{nm} from Technosys Equipments — ISO certified manufacturer in Pune, India. Custom builds, fast delivery, export worldwide. Get a free quote."[:155]
        h1 = f"{nm} Manufacturer in India"
        pk = f"{nm.lower()} manufacturer India"; sk = nm.lower()
    proposals.append({'scope':'Category','name':html.unescape(ct['name'])+f" ({ct['count']} products)",'url':url,
        'pr_title':t,'pr_desc':d,'pr_h1':h1,'primary_kw':pk,'secondary_kw':sk})

# ---------- HAND-AUTHORED: INDUSTRY PAGES (14) ----------
industry_url = {p['title']['rendered']: p['link'] for p in pages}
industries = {
 'Manufacturing':'manufacturing plants','Warehousing & Distribution':'warehouses & distribution centres',
 'Logistics & Transportation':'logistics & transport hubs','Construction':'construction sites',
 'Retail':'retail & store backrooms','Agriculture':'farms & agri-processing',
 'Healthcare':'hospitals & healthcare facilities','Food & Beverage':'food & beverage plants',
 'Automotive':'automotive & auto-component plants','Energy & Utilities':'energy & utility sites',
 'Mining & Extraction':'mining & extraction operations','E-commerce':'e-commerce fulfilment centres',
 'Pharmaceuticals':'pharmaceutical & clean-room facilities','Textiles':'textile & garment factories',
}
for raw_title, link in industry_url.items():
    base = c(raw_title).replace(' with Technosys','').strip()
    if base in industries:
        ctx = industries[base]
        t = f"Material Handling Equipment for {base} | Technosys"[:62]
        d = f"Material handling equipment built for {ctx}. Pallet trucks, stackers, forklifts & custom solutions from Technosys, India. Get an industry quote."[:155]
        h1 = f"Material Handling Equipment for the {base} Industry"
        pk = f"material handling equipment for {base.lower()}"
        sk = f"{base.lower()} material handling, warehouse equipment {base.lower()}"
        proposals.append({'scope':'Industry','name':base,'url':link,'pr_title':t,'pr_desc':d,'pr_h1':h1,'primary_kw':pk,'secondary_kw':sk})

# ---------- PRODUCTS: templated proposals + alt rule ----------
prod_alt = []
for p in prods:
    name = c(p['title']['rendered'])
    url = p['link']
    cat_ids = p.get('product_cat', []) or []
    cat_name = ''
    for cid in cat_ids:
        if cid in cat_by_id and cat_by_id[cid]['slug']!='uncategorized':
            cat_name = html.unescape(cat_by_id[cid]['name']); break
    t = f"{name} | {cat_name or 'Material Handling'} Manufacturer India"[:60]
    d = f"{name} from Technosys Equipments — {cat_name.lower() or 'material handling'} built in Pune, India. ISO certified, fast delivery. Request price & specs."[:155]
    h1 = name
    pk = f"{name.lower()}"
    sk = f"{(cat_name or 'material handling').lower()} manufacturer India, buy {name.lower()}"
    proposals.append({'scope':'Product','name':name,'url':url,'pr_title':t,'pr_desc':d,'pr_h1':h1,'primary_kw':pk,'secondary_kw':sk})
    # alt text rule for the product's featured image
    alt = f"{name} – {cat_name} manufacturer India | Technosys" if cat_name else f"{name} – Technosys Equipments India"
    prod_alt.append({'product':name,'url':url,'featured_media':p.get('featured_media'),'proposed_alt':alt[:125]})

# category archive existing meta (scraped separately)
try: catex = json.load(open('cat_existing.json'))
except: catex = {}

def trim_title(t):
    """Ensure <=60 chars; drop ' | Technosys' suffix first, then trim words."""
    if len(t)<=60: return t
    if ' | ' in t:
        base = t.rsplit(' | ',1)[0]
        if len(base)<=60: return base
        t = base
    while len(t)>60 and ' ' in t:
        t = t.rsplit(' ',1)[0]
    return t

# attach existing meta + enforce title length
for pr in proposals:
    pr['pr_title'] = trim_title(pr['pr_title'])
    if pr['url'] in catex:
        pr['ex_title'] = catex[pr['url']]['title']
        pr['ex_desc']  = catex[pr['url']]['desc']
        pr['ex_h1']    = catex[pr['url']]['h1']
    else:
        pr['ex_title'] = ex(pr['url'],'title')
        pr['ex_desc']  = ex(pr['url'],'desc')
        pr['ex_h1']    = ex(pr['url'],'h1')
    # flags
    pr['title_fix'] = len(pr['ex_title'])>60 or len(pr['ex_title'])==0
    pr['desc_fix']  = (len(pr['ex_desc'])>160 or len(pr['ex_desc'])<70)
    pr['h1_fix']    = (pr['ex_h1']!=1)

json.dump(proposals, open('proposals.json','w'), indent=1)
json.dump(prod_alt, open('product_alt.json','w'), indent=1)
print('Proposals:', len(proposals), '| Product alt drafts:', len(prod_alt))
from collections import Counter
print('By scope:', dict(Counter(p['scope'] for p in proposals)))
print('Need title fix:', sum(1 for p in proposals if p['title_fix']))
print('Need desc fix :', sum(1 for p in proposals if p['desc_fix']))
print('Need H1 fix   :', sum(1 for p in proposals if p['h1_fix']))
