#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any, Optional
from urllib.parse import urljoin, urlparse

import requests

TIMEOUT = 25
USER_AGENT = (
    "Mozilla/5.0 (X11; Linux x86_64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/150 Safari/537.36"
)


def make_session() -> requests.Session:
    s = requests.Session()
    s.headers.update({
        "User-Agent": USER_AGENT,
        "Accept": "application/json,text/plain,*/*",
        "Accept-Language": "pl-PL,pl;q=0.9,en;q=0.8",
    })
    return s


def get_json(s: requests.Session, url: str) -> Any:
    r = s.get(url, timeout=TIMEOUT)
    r.raise_for_status()
    r.encoding = "utf-8"
    return r.json()


def parse_price(text: Optional[str]) -> tuple[Optional[float], Optional[str]]:
    if not text:
        return None, None

    currency = (
        "GBP" if "£" in text else
        "EUR" if "€" in text else
        "USD" if "$" in text else
        None
    )

    m = re.search(r"\d[\d\s,.]*", text)
    if not m:
        return None, currency

    raw = m.group(0).strip().replace(" ", "").replace(",", "")
    try:
        return float(raw), currency
    except ValueError:
        return None, currency


def absolute_url(origin: str, value: Optional[str]) -> Optional[str]:
    if not value:
        return None
    if value.startswith(("http://", "https://", "data:")):
        return value
    return urljoin(origin + "/", value.lstrip("/"))


def get_nested(data: dict, *keys: str) -> Any:
    cur: Any = data
    for key in keys:
        if not isinstance(cur, dict):
            return None
        cur = cur.get(key)
    return cur


def normalize_project(
    item: dict,
    status: str,
    origin: str,
    language: str,
) -> dict:
    raw_link = (
        item.get("link")
        or item.get("url")
        or item.get("path")
        or item.get("href")
    )

    if raw_link:
        if raw_link.startswith(("http://", "https://")):
            project_url = raw_link
        else:
            # Projects.js itself prefixes the current language when the link
            # does not already contain a supported language prefix.
            supported = {"ar", "en", "fa", "pl", "ru", "tr"}
            path = raw_link if raw_link.startswith("/") else "/" + raw_link
            parts = [p for p in path.split("/") if p]
            if not parts or parts[0] not in supported:
                path = f"/{language}{path}"
            project_url = urljoin(origin + "/", path.lstrip("/"))
    else:
        project_url = None

    image = (
        item.get("image")
        or item.get("bgImage")
        or item.get("coverImage")
        or item.get("thumbnail")
    )

    price_text = (
        item.get("price")
        or item.get("startingPrice")
        or item.get("startPrice")
        or item.get("priceFrom")
    )
    price, currency = parse_price(price_text)

    slug = (
        Path(urlparse(project_url).path).name
        if project_url
        else None
    )

    return {
        "id": item.get("id"),
        "status": status,
        "slug": slug,
        "name": item.get("title") or item.get("name"),
        "location": item.get("location"),
        "description": item.get("description"),
        "starting_price_text": price_text,
        "starting_price": price,
        "currency": currency,
        "cover_image": absolute_url(origin, image),
        "project_url": project_url,
    }


def scrape_all_projects(
    all_projects_url: str,
    debug: bool = False,
    save_translation: Optional[Path] = None,
) -> dict:
    parsed = urlparse(all_projects_url)
    origin = f"{parsed.scheme}://{parsed.netloc}"

    parts = [p for p in parsed.path.split("/") if p]
    supported = {"ar", "en", "fa", "pl", "ru", "tr"}
    language = parts[0] if parts and parts[0] in supported else "en"

    # This is the source actually used by Projects-*.js:
    # r("projectsPage.projects.ongoing", {returnObjects:true})
    # r("projectsPage.projects.completed", {returnObjects:true})
    translation_url = (
        f"{origin}/locales/{language}/translation.json"
    )

    s = make_session()
    data = get_json(s, translation_url)

    if save_translation:
        save_translation.parent.mkdir(parents=True, exist_ok=True)
        save_translation.write_text(
            json.dumps(data, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )

    ongoing = get_nested(data, "projectsPage", "projects", "ongoing")
    completed = get_nested(data, "projectsPage", "projects", "completed")

    if not isinstance(ongoing, list):
        ongoing = []
    if not isinstance(completed, list):
        completed = []

    if not ongoing and not completed:
        raise RuntimeError(
            "translation.json nie zawiera "
            "projectsPage.projects.ongoing/completed"
        )

    projects = [
        normalize_project(x, "ongoing", origin, language)
        for x in ongoing if isinstance(x, dict)
    ]
    projects += [
        normalize_project(x, "completed", origin, language)
        for x in completed if isinstance(x, dict)
    ]

    warnings = []
    required = (
        "name",
        "location",
        "description",
        "starting_price_text",
        "cover_image",
        "project_url",
    )

    for project in projects:
        missing = [k for k in required if not project.get(k)]
        if missing:
            warnings.append({
                "id": project.get("id"),
                "slug": project.get("slug"),
                "missing": missing,
            })

    if debug:
        print(f"[CC] Language: {language}")
        print(f"[CC] Translation: {translation_url}")
        print(f"[CC] Ongoing: {len(ongoing)}")
        print(f"[CC] Completed: {len(completed)}")
        for p in projects:
            print(
                f"[CC] {p['status']:9} | "
                f"{p['name']!r} | {p['location']!r} | "
                f"{p['starting_price_text']!r} | {p['project_url']}"
            )

    return {
        "source": {
            "all_projects_url": all_projects_url,
            "translation_url": translation_url,
            "language": language,
        },
        "summary": {
            "projects": len(projects),
            "ongoing": len(ongoing),
            "completed": len(completed),
            "warnings": len(warnings),
        },
        "warnings": warnings,
        "projects": projects,
    }


def main() -> int:
    parser = argparse.ArgumentParser(
        description=(
            "Read Cyprus Constructions project cards from the same "
            "i18n JSON used by the /all-projects page."
        )
    )
    parser.add_argument(
        "url",
        nargs="?",
        default="https://www.cyprusconstructions.com/pl/all-projects",
    )
    parser.add_argument("-o", "--output", default="cyprus_all_projects.json")
    parser.add_argument("--debug", action="store_true")
    parser.add_argument(
        "--save-translation",
        nargs="?",
        const="translation.pl.json",
        help="Optionally save the raw translation JSON used by the page.",
    )
    args = parser.parse_args()

    result = scrape_all_projects(
        args.url,
        debug=args.debug,
        save_translation=(
            Path(args.save_translation)
            if args.save_translation
            else None
        ),
    )

    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(
        json.dumps(result, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )

    print("[CC] ===== SUMMARY =====")
    print(f"[CC] Projects:  {result['summary']['projects']}")
    print(f"[CC] Ongoing:   {result['summary']['ongoing']}")
    print(f"[CC] Completed: {result['summary']['completed']}")
    print(f"[CC] Warnings:  {result['summary']['warnings']}")
    print(f"[CC] Saved:     {output.resolve()}")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        raise SystemExit(130)
    except Exception as exc:
        print(f"\n[ERROR] {exc}", file=sys.stderr)
        raise SystemExit(1)
