# -*- coding: utf-8 -*-
"""Etapa 5 — extrage conținutul REAL din view-uri, verbatim, și îl scrie în seed_data.json.

Nimic nu e scris de mână: fiecare text vine din fișierul sursă, cu spațiile
normalizate exact cum le normalizează browserul (whitespace colapsat).
"""
import re, io, os, json

ROOT = r"C:\OpenServer\domains\localhost\cinova"
PHP = re.compile(r'<\?(?:=|php).*?\?>', re.S)


def src(rel):
    return io.open(os.path.join(ROOT, rel), encoding="utf-8").read()


def block(rel, start, end):
    return "\n".join(src(rel).split("\n")[start - 1:end])


def clean(html):
    """Elimină tagurile interioare și colapsează spațiile — ca la randare."""
    t = PHP.sub("", html)
    t = re.sub(r"<[^>]+>", " ", t)
    t = t.replace("&amp;", "&").replace("&nbsp;", " ")
    return re.sub(r"\s+", " ", t).strip()


def tags(html, *names):
    """Întoarce textul fiecărui tag de tipul cerut, în ordinea apariției."""
    pat = r"<(%s)\b[^>]*>(.*?)</\1>" % "|".join(names)
    return [clean(m.group(2)) for m in re.finditer(pat, html, re.S | re.I)]


def imgs(html):
    return re.findall(r"assests/([a-zA-Z0-9/._-]+)", html)


def icons(html):
    return re.findall(r'class="bi (bi-[a-z0-9-]+)"', html)


data = {}

# ---------------------------------------------------------------- pricing (3)
pr = block("views/home/index.php", 889, 1122)
cards = re.findall(r'<div class="pricing-plan__card">(.*?)(?=<div class="pricing-plan__card">|\Z)', pr, re.S)[:3]
data["pricing_plans"] = []
for i, c in enumerate(cards, 1):
    h3 = tags(c, "h3")
    p = tags(c, "p")
    h2 = tags(c, "h2")
    li = tags(c, "li")
    a = tags(c, "a")
    ic = icons(c)
    price = h2[0] if h2 else ""
    m = re.match(r"(\S+)\s*(.*)", price)
    data["pricing_plans"].append({
        "alias": re.sub(r"[^a-z0-9]+", "-", h3[0].lower()).strip("-"),
        "icon_class": ic[0] if ic else None,
        "price": m.group(1) if m else price,
        "period": m.group(2) if m else "",
        "sort_order": i,
        "tr": {"name": h3[0], "desc_min": p[0] if p else "",
               "button_text": a[0] if a else "", "features_text": "\n".join(li)},
    })

# ----------------------------------------------------------- testimonials (4)
ts = block("views/home/index.php", 1123, 1270)
cards = re.findall(r'<div class="testimonial-card">(.*?)(?=<div class="swiper-slide|\Z)', ts, re.S)
data["testimonials"] = []
for i, c in enumerate(cards, 1):
    h3 = tags(c, "h3")
    p = tags(c, "p")
    im = imgs(c)
    if not h3:
        continue
    # numără stelele DOAR în blocul de rating al cardului: ultimul card se întinde
    # până la \Z și ar aduna stelele din tot restul paginii
    rat = re.search(r'<div class="what-we-do__box-rating">(.*?)</div>', c, re.S)
    stars = len(re.findall(r"bi-star-fill", rat.group(1))) if rat else 5
    data["testimonials"].append({
        "alias": re.sub(r"[^a-z0-9]+", "-", h3[0].lower()).strip("-"),
        "avatar_image": im[0] if im else None,
        "rating": "%.1f" % min(stars, 5),
        "sort_order": i,
        "tr": {"author_name": h3[0], "author_role": p[-1] if len(p) > 1 else "",
               "content_text": p[0] if p else ""},
    })

# --------------------------------------------------------------- features (3)
ft = block("views/home/index.php", 510, 586)
# atenție: `our-feature__card-container` / `-text` / `-img` NU sunt carduri
cards = re.findall(r'<div class="our-feature__card(?:"| [^"]*")>(.*?)(?=<div class="our-feature__card(?:"| )|\Z)',
                   ft, re.S)
data["features"] = []
for i, c in enumerate(cards, 1):
    h3 = tags(c, "h3")
    p = tags(c, "p")
    a = tags(c, "a")
    im = imgs(c)
    if not h3:
        continue
    data["features"].append({
        "alias": "feature-%d" % (len(data["features"]) + 1),
        "main_image": im[0] if im else None,
        "sort_order": len(data["features"]) + 1,
        "tr": {"name": h3[0], "desc_min": p[0] if p else "", "button_text": a[0] if a else ""},
    })

# ------------------------------------------------------------------ steps (4)
st = block("views/about/index.php", 175, 238)
cards = re.findall(r'<div class="how-it-works__card">(.*?)(?=<div class="how-it-works__card"|\Z)', st, re.S)
data["steps"] = []
for i, c in enumerate(cards, 1):
    h3 = tags(c, "h3")
    p = tags(c, "p")
    im = imgs(c)
    data["steps"].append({
        "alias": "step-%d" % i,
        "icon_image": im[0] if im else None,
        "number": "%02d" % i,
        "sort_order": i,
        "tr": {"name": h3[0] if h3 else "", "desc_min": p[0] if p else ""},
    })

# ---------------------------------------------------------- approach cards (3)
ap = block("views/about/index.php", 133, 174)
cards = re.findall(r'<div class="our-approuch__card(?:"| [^"]*")>(.*?)(?=<div class="our-approuch__card(?:"| )|\Z)',
                   ap, re.S)
data["approach_cards"] = []
for i, c in enumerate(cards, 1):
    h3 = tags(c, "h3")
    p = tags(c, "p")
    im = imgs(c)
    if not h3:
        continue
    data["approach_cards"].append({
        "alias": re.sub(r"[^a-z0-9]+", "-", h3[0].lower()).strip("-"),
        "icon_image": im[0] if im else None,
        "sort_order": i,
        "tr": {"name": h3[0], "desc_min": p[0] if p else ""},
    })

# --------------------------------------------------------------- partners (5)
pb = block("views/home/index.php", 38, 102)
logos = []
for lg in re.findall(r"assests/logo/([a-zA-Z0-9._-]+)", pb):
    if lg not in logos:
        logos.append(lg)
data["partners"] = [{"alias": os.path.splitext(l)[0], "logo_image": "logo/" + l,
                     "url": "", "sort_order": i} for i, l in enumerate(logos, 1)]

# --------------------------------------------------------------- benefits (2)
wb = block("views/home/index.php", 819, 856)
data["benefits"] = [{"alias": "benefit-%d" % i, "sort_order": i, "tr": {"name": t}}
                    for i, t in enumerate(tags(wb, "li"), 1)]

# ---------------------------------------------------------- marquee items (4)
ws = block("views/home/index.php", 857, 888)
# doar span-urile din banda propriu-zisă; designul o repetă de 2× pentru efectul de scroll
ticker = re.search(r'<div class="watch-story__ticker-content">(.*?)</div>', ws, re.S)
seen, marq = set(), []
for t in tags(ticker.group(1) if ticker else "", "span"):
    if t and t not in seen:
        seen.add(t)
        marq.append(t)
data["marquee_items"] = [{"alias": re.sub(r"[^a-z0-9]+", "-", t.lower()).strip("-"),
                          "sort_order": i, "tr": {"name": t}} for i, t in enumerate(marq, 1)]

# --------------------------------------------------- service showcase (5 taburi)
sv = block("views/home/index.php", 200, 509)
# `--selected` stă în atributul class, ÎNAINTE de data-tab — capturez tot <li>
tabs = [(m.group(1), m.group(0))
        for m in re.finditer(r'<li class="our-service__navigation-tab[^"]*"\s+data-tab="([a-z]+)".*?</li>',
                             sv, re.S)]
# lookahead-ul trebuie să ceară `data-card`, altfel se oprește la primul
# `our-service__card-section-1` din interiorul cardului
cards = re.findall(
    r'<div class="our-service__card[^"]*"\s+data-card="([a-z]+)">'
    r'(.*?)(?=<div class="our-service__card[^"]*"\s+data-card=|\Z)', sv, re.S)
card_by_key = {k: v for k, v in cards}
data["service_showcase"] = []
for i, (key, tabhtml) in enumerate(tabs, 1):
    c = card_by_key.get(key, "")
    h3 = tags(c, "h3")
    p = tags(c, "p")
    li = tags(c, "li")
    a = tags(c, "a")
    ic = icons(tabhtml)
    data["service_showcase"].append({
        "alias": key, "card_key": key,
        "icon_class": ic[0] if ic else None,
        "is_default": "1" if "--selected" in tabhtml else "0",
        "counter_value": h3[2] if len(h3) > 2 else "",
        "sort_order": i,
        "tr": {"tab_label": clean(tabhtml), "name": h3[0] if h3 else "",
               "desc_min": p[0] if p else "", "button_text": a[0] if a else "",
               "offer_title": h3[1] if len(h3) > 1 else "",
               "offer_text": "\n".join(li),
               "counter_label": p[-1] if len(p) > 1 else ""},
    })

# --------------------------------------------------------- project showcase (8)
ps = block("views/home/index.php", 587, 710)
cards = re.findall(r'class="our-projects__card">(.*?)</a>', ps, re.S)
data["project_showcase"] = []
for i, c in enumerate(cards, 1):
    # categoria e <p class="text-uppercase">, descrierea e <h3>
    p = tags(c, "p")
    h3 = tags(c, "h3")
    im = imgs(c)
    data["project_showcase"].append({
        "alias": "project-card-%d" % i,
        "main_image": im[0] if im else None,
        "sort_order": i,
        "tr": {"category": p[0] if p else "", "desc_min": h3[0] if h3 else ""},
    })

# ----------------------------------------------------- project challenges (2)
pc = block("views/projects/view.php", 223, 265)
blocks = re.split(r'(?=<h3>)', pc)
data["project_challenges"] = []
n = 0
for b in blocks:
    if "<h3>" not in b:
        continue
    n += 1
    h3 = tags(b, "h3")
    p = tags(b, "p")
    li = tags(b, "li")
    data["project_challenges"].append({
        "alias": re.sub(r"[^a-z0-9]+", "-", h3[0].lower()).strip("-"),
        "sort_order": n,
        "tr": {"name": h3[0], "desc_min": p[0] if p else "", "points_text": "\n".join(li)},
    })

io.open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "seed_data.json"),
        "w", encoding="utf-8").write(json.dumps(data, ensure_ascii=False, indent=2))

for k, v in data.items():
    print("%-22s %d" % (k, len(v)))
