#!/usr/bin/env python3
"""
Heritage Voice Phase 2
Chạy script này trên server để tự động thêm section Partners
vào home.html và detail.html

Chạy: python3 /home/tranhiep/tads.ctv.hanoi.vn/patch_phase2.py
"""

import re, os, shutil
from datetime import datetime

BASE = '/home/tranhiep/tads.ctv.hanoi.vn'

def backup(path):
    bak = path + '.bak.' + datetime.now().strftime('%Y%m%d_%H%M%S')
    shutil.copy2(path, bak)
    print(f'  📦 Backup: {bak}')

def patch_home():
    path = os.path.join(BASE, 'home.html')
    print(f'\n🔧 Patching {path}')
    backup(path)

    with open(path, 'r', encoding='utf-8') as f:
        content = f.read()

    # ── 1. Thêm CSS vào cuối <style> ──────────────────────────
    CSS = """
/* ── PARTNER SECTION (Phase 2) ── */
.partner-h-card{flex-shrink:0;width:170px;border-radius:14px;overflow:hidden;background:#fff;box-shadow:0 2px 10px rgba(0,0,0,.08);cursor:pointer;border:1px solid #F0EDE8;transition:transform .15s;}
.partner-h-card:active{transform:scale(.97);}
.partner-h-card-img{width:100%;height:100px;background:#FDF6EE;display:flex;align-items:center;justify-content:center;font-size:36px;}
.partner-h-card-img img{width:100%;height:100%;object-fit:cover;}
.partner-h-card-body{padding:10px;}
.partner-h-card-type{font-size:9px;font-weight:700;color:#C0622A;text-transform:uppercase;letter-spacing:.4px;margin-bottom:3px;}
.partner-h-card-name{font-size:13px;font-weight:700;color:#2C1A0E;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}
.partner-h-card-dist{font-size:10px;font-weight:700;color:#888;margin-top:3px;}
.partner-h-card-hours{font-size:9px;font-weight:700;margin-top:3px;}
.partner-h-card-hours.open{color:#2E7D32;}
.partner-h-card-hours.closed{color:#C62828;}
.partner-register-cta{background:linear-gradient(135deg,#8B3E18,#D4A047);border-radius:16px;padding:16px;margin-bottom:20px;display:flex;align-items:center;gap:12px;cursor:pointer;box-shadow:0 4px 16px rgba(139,62,24,.25);text-decoration:none;}
.partner-register-cta-icon{font-size:32px;flex-shrink:0;}
.partner-register-cta-title{font-size:14px;font-weight:800;color:#fff;line-height:1.3;margin-bottom:2px;}
.partner-register-cta-sub{font-size:11px;color:rgba(255,255,255,.75);}
.partner-register-cta-arrow{margin-left:auto;font-size:20px;color:rgba(255,255,255,.7);flex-shrink:0;}
"""
    if 'partner-h-card' not in content:
        content = content.replace('</style>', CSS + '</style>', 1)
        print('  ✅ Đã thêm CSS')
    else:
        print('  ⚠️  CSS đã có')

    # ── 2. Thêm Zone Partners sau featuredZone ─────────────────
    PARTNER_ZONE = """
    <!-- ZONE: ĐỐI TÁC GẦN ĐÂY (Phase 2) -->
    <div id="partnerZone" style="display:none;margin-bottom:20px;">
      <div class="sec-hdr">
        <div class="sec-title">🍜 Ăn uống & Lưu trú gần đây</div>
        <a href="partners-nearby.html" class="sec-more">Xem tất cả →</a>
      </div>
      <div class="h-scroll" id="partnerScroll"></div>
    </div>

    <!-- ZONE: ĐĂNG KÝ ĐỐI TÁC CTA (Phase 2) -->
    <div id="partnerCtaZone" style="margin-bottom:20px;">
      <a href="partner-register.html" class="partner-register-cta">
        <div class="partner-register-cta-icon">🤝</div>
        <div>
          <div class="partner-register-cta-title">Bạn có nhà hàng / khách sạn?</div>
          <div class="partner-register-cta-sub">Đăng ký đối tác Heritage Voice — Miễn phí</div>
        </div>
        <div class="partner-register-cta-arrow">›</div>
      </a>
    </div>
"""
    if 'partnerZone' not in content:
        # Tìm điểm chèn: sau closing div của featuredZone
        anchor = '    <!-- ZONE: TẤT CẢ -->'
        if anchor in content:
            content = content.replace(anchor, PARTNER_ZONE + anchor)
            print('  ✅ Đã thêm Partner Zone & CTA')
        else:
            # Fallback: tìm allZone
            anchor2 = '<div id="allZone">'
            if anchor2 in content:
                content = content.replace(anchor2, PARTNER_ZONE + '\n    ' + anchor2)
                print('  ✅ Đã thêm Partner Zone & CTA (fallback)')
            else:
                print('  ❌ Không tìm thấy anchor để chèn Zone')
    else:
        print('  ⚠️  Partner Zone đã có')

    # ── 3. Thêm script trước </body> ──────────────────────────
    SCRIPT = """
<script>
/* Phase 2: Partner Zone in home.html (IIFE) */
(function(){
  const API='https://tads.ctv.hanoi.vn/api';
  const ICONS={restaurant:'🍜',hotel:'🏨',guesthouse:'🏡',cafe:'☕',transport:'🚌',shop:'🛍️',other:'📦'};
  const LABELS={restaurant:'Nhà hàng',hotel:'Khách sạn',guesthouse:'Homestay',cafe:'Cafe',transport:'Phương tiện',shop:'Cửa hàng',other:'Khác'};

  const _orig=window.getUserLocation;
  window.getUserLocation=function(){
    if(_orig) _orig.call(this);
    setTimeout(loadPartners,1200);
  };
  window.addEventListener('DOMContentLoaded',()=>{
    if(!_orig) setTimeout(loadPartners,1200);
  });

  async function loadPartners(){
    try{
      const params=new URLSearchParams({limit:10});
      const gps=await gpsQuick();
      if(gps){params.set('lat',gps.lat);params.set('lng',gps.lng);params.set('radius','3000');}
      else{params.set('lat','21.0285');params.set('lng','105.8542');params.set('radius','5000');}
      const r=await fetch(`${API}/partners/nearby?${params}`);
      const d=await r.json();
      const items=d.data||[];
      if(!items.length) return;
      renderCards(items);
      document.getElementById('partnerZone').style.display='block';
    }catch(e){}
  }

  function renderCards(items){
    const el=document.getElementById('partnerScroll');
    if(!el) return;
    el.innerHTML=items.map(p=>{
      const img=p.images&&p.images[0]
        ?`<img src="${x(p.images[0])}" loading="lazy"/>`
        :`<div style="width:100%;height:100px;background:#FDF6EE;display:flex;align-items:center;justify-content:center;font-size:36px;">${ICONS[p.type]||'📍'}</div>`;
      const dist=p.distance_m>=1000?(p.distance_m/1000).toFixed(1)+'km':p.distance_m+'m';
      const hrs=hoursStatus(p.open_hours);
      return `<div class="partner-h-card" onclick="window.location.href='partners-nearby.html?open=${x(p.uuid)}'">
        <div class="partner-h-card-img">${img}</div>
        <div class="partner-h-card-body">
          <div class="partner-h-card-type">${LABELS[p.type]||p.type}</div>
          <div class="partner-h-card-name">${x(p.name)}</div>
          <div class="partner-h-card-dist">📍 ${dist}</div>
          ${hrs?`<div class="partner-h-card-hours ${hrs.c}">${hrs.t}</div>`:''}
        </div>
      </div>`;
    }).join('');
  }

  function hoursStatus(h){
    if(!h) return null;
    try{
      const hours=typeof h==='string'?JSON.parse(h):h;
      const now=new Date();
      const key=['sun','mon','tue','wed','thu','fri','sat'][now.getDay()];
      const t=hours[key];
      if(!t) return{c:'closed',t:'🔴 Hôm nay đóng'};
      const nowM=now.getHours()*60+now.getMinutes();
      const[oh,om]=t.open.split(':').map(Number);
      const[ch,cm]=t.close.split(':').map(Number);
      return nowM>=oh*60+om&&nowM<ch*60+cm
        ?{c:'open',t:`🟢 Mở đến ${t.close}`}
        :{c:'closed',t:`🔴 Mở lúc ${t.open}`};
    }catch(e){return null;}
  }

  function gpsQuick(){return new Promise(res=>{if(!navigator.geolocation){res(null);return;}navigator.geolocation.getCurrentPosition(p=>res({lat:p.coords.latitude,lng:p.coords.longitude}),()=>res(null),{timeout:3000,maximumAge:120000});});}
  function x(s){if(!s)return'';return String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));}
})();
</script>
"""
    if 'partnerScroll' not in content or 'Phase 2: Partner Zone in home' not in content:
        content = content.replace('</body>', SCRIPT + '\n</body>')
        print('  ✅ Đã thêm script')
    else:
        print('  ⚠️  Script đã có')

    with open(path, 'w', encoding='utf-8') as f:
        f.write(content)
    print('  ✅ home.html đã được cập nhật')


def patch_detail():
    path = os.path.join(BASE, 'detail.html')
    print(f'\n🔧 Patching {path}')
    backup(path)

    with open(path, 'r', encoding='utf-8') as f:
        content = f.read()

    # ── 1. Thêm tab button ─────────────────────────────────────
    TAB_BTN = """<button class="hv-page-tab" onclick="switchTab('nearby',this)">📍 <span>Gần đây</span></button>
  </div>"""
    if "switchTab('nearby'" not in content:
        # Tìm closing </div> của hv-page-tabs
        content = re.sub(
            r"(<button[^>]*switchTab\('map'[^>]*>.*?</button>\s*)(</div>)",
            r"\1\n  " + "<button class=\"hv-page-tab\" onclick=\"switchTab('nearby',this)\">📍 <span>Gần đây</span></button>" + r"\n  \2",
            content, flags=re.DOTALL
        )
        print('  ✅ Đã thêm tab button')
    else:
        print('  ⚠️  Tab button đã có')

    # ── 2. Thêm tab panel sau tabMap ──────────────────────────
    TAB_PANEL = """
  <!-- TAB: NEARBY (Phase 2) -->
  <div id="tabNearby" class="tab-content" style="display:none;padding:0;">
    <div style="padding:10px 14px;background:#fff;border-bottom:1px solid var(--border-light);display:flex;gap:7px;overflow-x:auto;scrollbar-width:none;">
      <button class="hv-tab active" data-ntype="" onclick="nearbySetType('',this)">🗂 Tất cả</button>
      <button class="hv-tab" data-ntype="restaurant" onclick="nearbySetType('restaurant',this)">🍜 Ăn uống</button>
      <button class="hv-tab" data-ntype="hotel"      onclick="nearbySetType('hotel',this)">🏨 Lưu trú</button>
      <button class="hv-tab" data-ntype="cafe"       onclick="nearbySetType('cafe',this)">☕ Cafe</button>
      <button class="hv-tab" data-ntype="shop"       onclick="nearbySetType('shop',this)">🛍️ Mua sắm</button>
    </div>
    <div id="nearbyTabList" style="padding:12px 14px 16px;">
      <div class="hv-loading"><div class="hv-spinner"></div><div>Đang tìm...</div></div>
    </div>
    <div style="padding:0 14px 20px;display:flex;flex-direction:column;gap:8px;">
      <a id="nearbyViewAll" href="partners-nearby.html" class="hv-btn hv-btn-secondary" style="width:100%;justify-content:center;">🗺 Xem tất cả đối tác gần đây →</a>
      <a href="partner-register.html" style="text-align:center;font-size:12px;color:var(--green-2);font-weight:600;padding:8px;display:block;">🤝 Đăng ký cơ sở của bạn tại đây</a>
    </div>
  </div>
"""
    if 'tabNearby' not in content:
        # Chèn sau tabMap closing div
        # Tìm </div> đầu tiên sau id="tabMap"
        content = re.sub(
            r'(id="tabMap"[^>]*>.*?</div>)(\s*<!-- FOOTER -->)',
            r'\1' + TAB_PANEL + r'\2',
            content, flags=re.DOTALL, count=1
        )
        print('  ✅ Đã thêm tab panel')
    else:
        print('  ⚠️  Tab panel đã có')

    # ── 3. Thêm script trước </body> ──────────────────────────
    SCRIPT = """
<script>
/* Phase 2: Nearby Tab in detail.html (IIFE) */
(function(){
  const API='https://tads.ctv.hanoi.vn/api';
  let _loaded=false,_type='',_data=[];
  const ICONS={restaurant:'🍜',hotel:'🏨',guesthouse:'🏡',cafe:'☕',transport:'🚌',shop:'🛍️',other:'📦'};
  const LABELS={restaurant:'Nhà hàng',hotel:'Khách sạn',guesthouse:'Homestay',cafe:'Cafe',transport:'Phương tiện',shop:'Cửa hàng',other:'Khác'};
  const PRICE=['','$','$$','$$$','$$$$'];

  const _orig=window.switchTab;
  window.switchTab=function(tab,btn){
    _orig.call(this,tab,btn);
    if(tab==='nearby'&&!_loaded){_loaded=true;loadNearby();}
  };
  window.nearbySetType=function(type,btn){
    _type=type;
    document.querySelectorAll('[data-ntype]').forEach(b=>b.classList.remove('active'));
    btn.classList.add('active');
    render(_data);
  };

  async function loadNearby(){
    const el=document.getElementById('nearbyTabList');
    if(!el) return;
    const p=new URLSearchParams(location.search);
    const siteId=p.get('site')||(JSON.parse(sessionStorage.getItem('hv_site')||'null')?.id)||null;
    const siteName=document.getElementById('heroName')?.textContent||'';
    const linkAll=document.getElementById('nearbyViewAll');
    if(linkAll&&siteId) linkAll.href=`partners-nearby.html?site_id=${encodeURIComponent(siteId)}&site_name=${encodeURIComponent(siteName)}`;
    try{
      const params=new URLSearchParams({limit:10});
      if(siteId) params.set('site_id',siteId);
      const gps=await gpsQuick();
      if(gps){params.set('lat',gps.lat);params.set('lng',gps.lng);}
      if(!siteId) params.set('radius','2000');
      const tok=localStorage.getItem('hv_token')||'';
      const hdrs=tok?{Authorization:'Bearer '+tok}:{};
      const r=await fetch(`${API}/partners/nearby?${params}`,{headers:hdrs});
      const d=await r.json();
      _data=d.data||[];
      render(_data);
    }catch(e){
      el.innerHTML='<div class="hv-empty"><div class="hv-empty-icon">📍</div><div>Chưa có đối tác trong khu vực này.</div></div>';
    }
  }

  function render(all){
    const el=document.getElementById('nearbyTabList');
    if(!el) return;
    const items=_type?all.filter(p=>p.type===_type):all;
    if(!items.length){el.innerHTML='<div class="hv-empty"><div class="hv-empty-icon">🔍</div><div style="font-weight:700;margin-bottom:4px;">Chưa có đối tác</div><div style="font-size:12px;">Khu vực này chưa có đối tác Heritage Voice.</div></div>';return;}
    el.innerHTML=items.map(p=>{
      const img=p.images&&p.images[0]
        ?`<img src="${x(p.images[0])}" style="width:54px;height:54px;border-radius:10px;object-fit:cover;flex-shrink:0;" loading="lazy"/>`
        :`<div style="width:54px;height:54px;border-radius:10px;background:#FDF6EE;display:flex;align-items:center;justify-content:center;font-size:26px;flex-shrink:0;">${ICONS[p.type]||'📍'}</div>`;
      const dist=p.distance_m>=1000?(p.distance_m/1000).toFixed(1)+'km':p.distance_m+'m';
      const rating=p.avg_rating?`<span style="color:#F5A623;font-weight:700;font-size:11px;">★ ${p.avg_rating}</span>`:'';
      return `<div style="display:flex;gap:10px;padding:10px 0;border-bottom:1px solid #F0EDE8;cursor:pointer;align-items:center;" onclick="window.location.href='partners-nearby.html?open=${x(p.uuid)}'">
        ${img}
        <div style="flex:1;min-width:0;">
          <div style="font-size:13px;font-weight:700;color:#2C1A0E;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${x(p.name)}</div>
          <div style="font-size:11px;color:#888;margin-top:2px;">${LABELS[p.type]||p.type} · 📍${dist}${p.avg_rating?' · '+rating:''} · <span style="font-weight:700;">${PRICE[p.price_range]||''}</span></div>
          <div style="font-size:10px;color:#aaa;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">📌 ${x(p.address)}</div>
        </div>
        <span style="font-size:18px;color:#aaa;flex-shrink:0;">›</span>
      </div>`;
    }).join('');
  }

  function gpsQuick(){return new Promise(res=>{if(!navigator.geolocation){res(null);return;}navigator.geolocation.getCurrentPosition(p=>res({lat:p.coords.latitude,lng:p.coords.longitude}),()=>res(null),{timeout:3000,maximumAge:120000});});}
  function x(s){if(!s)return'';return String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));}
})();
</script>
"""
    if 'Phase 2: Nearby Tab in detail' not in content:
        content = content.replace('</body>', SCRIPT + '\n</body>')
        print('  ✅ Đã thêm script')
    else:
        print('  ⚠️  Script đã có')

    with open(path, 'w', encoding='utf-8') as f:
        f.write(content)
    print('  ✅ detail.html đã được cập nhật')


if __name__ == '__main__':
    print('🚀 Heritage Voice Phase 2 — Patch home.html & detail.html')
    patch_home()
    patch_detail()
    print('\n✅ Hoàn tất! Kiểm tra lại trên browser.')
