"""Conservative SoccerRating authenticated browser connector.

Only imports the upcoming 'Betting Picks' section, never 'Last 250 Matches'.
The caller (soccer_importer) handles duplicate detection and the review queue.
Requires Beautiful Soup, Playwright, and locally installed Microsoft Edge.
This connector does not bypass site access controls or store login passwords.
"""
from __future__ import annotations

import re
import sys
import time
from pathlib import Path
from urllib.parse import urlsplit

from bs4 import BeautifulSoup
from soccer_importer import STRATEGIES

ROOT = Path(__file__).resolve().parent
import os
if os.name == "nt" and ROOT.name.casefold() == "football main app" and ROOT.parent.name.casefold() == "desktop":
    PROFILE = ROOT.parent.parent / "FootballAnalytics_BrowserProfile"
else:
    PROFILE = ROOT / 'soccerrating_browser_profile'
SOURCE = 'https://www.soccer-rating.com/tips/'


class SourceUnavailable(RuntimeError):
    pass


ODD_RE = re.compile(r'\d{1,3}(?:[.,]\d{1,3})?')
DAY_RE = re.compile(r'(?<!\d)(\d{4}-\d{2}-\d{2}|\d{1,2}[./]\d{1,2}(?:[./]\d{2,4})?)(?!\d)')
# Source-visible competition codes are evidence labels, never league/category votes.
SOURCE_COMPETITION_CODE_RE = re.compile(r'[A-Z]{2,6}[0-9]{1,3}')
FIXTURE_RE = re.compile(r'^(.{2,120}?)\s+(?:-|–|—|vs\.?|v)\s+(.{2,120}?)$', re.I)
SEPARATOR = {'-', '–', '—', 'vs', 'vs.', 'VS', 'v', 'V'}
HISTORY_RE = re.compile(r'\blast\s+250\s+matches\b|\bbetting\s+strategy\s+history\b', re.I)
# SoccerRating renders an explicit red notice instead of a Betting Picks table
# for strategies without any upcoming matches (confirmed on Strategy 2.05).
NO_PICKS_RE = re.compile(r'\bsorry\s*,?\s*we\s+have\s+no\s+new\s+betting\s+picks\b', re.I)
CREATOR_RE = re.compile(r'\bfootball\s+strategy\s+creator\b', re.I)

# These are the seven account-owned strategy URLs supplied by the user.
# Never derive strategy IDs from odds or follow a similarly named third-party link.
STRATEGY_URLS = {
    '2.00': 'https://www.soccer-rating.com/tips/2-0/41768/',
    '2.05': 'https://www.soccer-rating.com/tips/2-05/41770/',
    '2.10': 'https://www.soccer-rating.com/tips/2-10/41769/',
    '2.15': 'https://www.soccer-rating.com/tips/2-15/41827/',
    '2.20': 'https://www.soccer-rating.com/tips/2-20/41799/',
    '2.25': 'https://www.soccer-rating.com/tips/2-25/41826/',
    '2.30': 'https://www.soccer-rating.com/tips/2-30/41822/',
}
if set(STRATEGY_URLS) != set(STRATEGIES):
    raise RuntimeError('The SoccerRating URL mapping must cover exactly the seven configured strategies.')


def _valid_strategy_target(actual_url, expected_url):
    """Allow only a fully verified HTTPS strategy page, not a redirected login/index."""
    actual, expected = urlsplit(actual_url), urlsplit(expected_url)
    return (actual.scheme == expected.scheme == 'https' and
            actual.hostname == expected.hostname == 'www.soccer-rating.com' and
            actual.port is None and actual.path.rstrip('/') == expected.path.rstrip('/') and
            not actual.username and not actual.password)


def _verify_strategy_title(title, strategy):
    """Reject an explicitly conflicting numeric page title, if the site provides one.

    The real pages use titles such as '2.20 - 90.00% Payout'. The title can also
    be generic, in which case the exact URL + Betting Picks header are required.
    """
    m = re.match(r'^\s*(2(?:[.,]\d{1,2})?)\s*(?:[-–—|]|$)', str(title or ''))
    if m and abs(float(m.group(1).replace(',', '.')) - float(strategy)) > 0.001:
        raise SourceUnavailable('Strategy page title disagrees with the configured source URL.')

# The document-load event can precede the Betting Picks table or the
# explicit no-picks notice. Wait for either *verified* content state, without
# issuing additional requests or treating a missing table as an empty result.
READY_CONTENT_JS = r"""() => {
  const foundHeader = [...document.querySelectorAll('tr')].some(row => {
    const cells=[...row.children].filter(el=>el.matches('td,th')).map(el=>el.textContent.trim().toLowerCase());
    const text=cells.join(' ').replace(/\s+/g,' ');
    return text.includes('betting picks') && text.includes('date') &&
      (cells.includes('1') && cells.includes('x') && cells.includes('2') || /\b1\s+x\s+2\b/.test(text));
  });
  if (foundHeader) return true;
  const text=(document.body?.innerText || '').replace(/\s+/g,' ').toLowerCase();
  return text.includes('football strategy creator') &&
    text.includes('last 250 matches') &&
    /sorry\s*,?\s*we\s+have\s+no\s+new\s+betting\s+picks/.test(text);
}"""

def _visible_empty_notice(page):
    """Recognize the no-picks notice in the *rendered* page, not just HTML source.

    On SoccerRating Strategy 2.05, Playwright confirmed that body.innerText
    contains this notice even though the HTML-table parser reported no header.
    Require independent page markers so missing/incomplete pages stay FAILED.
    The caller has already verified the exact HTTPS strategy URL and title.
    """
    try:
        visible = _clean(page.locator('body').inner_text(timeout=3000))
    except Exception:
        return False
    return bool(NO_PICKS_RE.search(visible) and CREATOR_RE.search(visible)
                and HISTORY_RE.search(visible))


def _parse_after_ready(page):
    """Wait for verified page content; prefer its explicit no-picks notice.

    A real Betting Picks table still goes through strict HTML row parsing;
    historical match rows are never used to populate the import queue.
    """
    try:
        page.wait_for_function(READY_CONTENT_JS, timeout=6500)
    except Exception:
        # Parsing below will still fail closed if neither supported state exists.
        pass

    html = page.content()
    if _visible_empty_notice(page):
        # Do not hide a genuine Betting Picks parsing problem if a table exists.
        soup = BeautifulSoup(html, 'html.parser')
        if not any(_is_picks_header(row) for row in soup.find_all('tr')):
            return []

    return parse_betting_picks(html)


def _clean(text):
    return re.sub(r'\s+', ' ', str(text).replace('\xa0', ' ')).strip()


def _cells(row):
    return [tag for tag in row.find_all(['td', 'th'], recursive=False)]


def _text(cell):
    return _clean(cell.get_text(' ', strip=True))


def _price(raw):
    raw = _clean(raw)
    if not ODD_RE.fullmatch(raw):
        return None
    value = float(raw.replace(',', '.'))
    return value if 1.0 < value <= 1000 else None


def _odds_from_cells(cells):
    """Return (odds, index of first price cell) without reading stake columns.

    SoccerRating has served both three separate 1/X/2 cells and a single cell
    containing three values. Never read numeric substrings from arbitrary text.
    """
    for i, cell in enumerate(cells):
        # Usual case: 3 consecutive separate odds cells.
        if i + 2 < len(cells):
            values = [_price(_text(x)) for x in cells[i:i + 3]]
            if all(v is not None for v in values):
                return values, i
        # Alternative: 1/X/2 presented in one cell, separated by whitespace.
        fragments = _text(cell).split()
        if len(fragments) == 3:
            values = [_price(frag) for frag in fragments]
            if all(v is not None for v in values):
                return values, i
    return None, None


def _teams_from_cells(cells):
    # Prefer explicitly linked team names, as SoccerRating can place the league
    # code and the two teams within the same HTML cell.
    for cell in cells:
        anchors = [_clean(a.get_text(' ', strip=True)) for a in cell.find_all('a')]
        anchors = [a for a in anchors if 2 <= len(a) <= 120]
        if len(anchors) == 2 and FIXTURE_RE.search(_text(cell)):
            return anchors[0], anchors[1]

    # Common table structure: 'Home - Away' in one cell.
    for cell in reversed(cells):
        match = FIXTURE_RE.fullmatch(_text(cell))
        if match:
            return _clean(match.group(1)), _clean(match.group(2))

    # Alternative structure: separate Home, '-', Away cells.
    parts = [_text(cell) for cell in cells]
    for j in range(1, len(parts) - 1):
        if parts[j] in SEPARATOR:
            return parts[j - 1], parts[j + 1]
    return None, None


def _match_row(row):
    cells = _cells(row)
    odds, offset = _odds_from_cells(cells)
    if odds is None:
        return None
    leading = cells[:offset]
    date = next((m.group(1) for cell in leading if (m := DAY_RE.search(_text(cell)))), None)
    if not date:
        return None
    home, away = _teams_from_cells(leading)
    if not home or not away or home.casefold() == away.casefold():
        return None
    if any(len(x) > 120 for x in (home, away)):
        return None
    # SoccerRating's actual Betting Picks rows repeat codes such as SW1/CL1
    # in two independent cells before the fixture. Accept only agreement.
    codes = [_text(cell) for cell in leading
             if SOURCE_COMPETITION_CODE_RE.fullmatch(_text(cell))]
    source_code = codes[0] if len(codes) == 2 and codes[0] == codes[1] else ''
    return {'date': date, 'home': home, 'away': away,
            'homeOdds': odds[0], 'drawOdds': odds[1], 'awayOdds': odds[2],
            'sourceCompetitionCode': source_code}


def _is_picks_header(row):
    parts = [_text(c).lower() for c in _cells(row)]
    content = ' '.join(parts)
    # The sidebar also has a link named 'Betting Picks'. Avoid treating it as
    # the table header: the actual header includes Date and odds columns.
    return ('betting picks' in content and 'date' in content
            and (all(x in parts for x in ('1', 'x', '2'))
                 or bool(re.search(r'\b1\s+x\s+2\b', content))))


def _looks_like_match(row):
    cells = _cells(row)
    parts = [_text(c) for c in cells]
    return bool(parts and any(DAY_RE.search(p) for p in parts)
                and (any(ODD_RE.fullmatch(p) for p in parts)
                     or any(len(p.split()) == 3 and all(_price(x) is not None for x in p.split()) for p in parts)))


def parse_betting_picks(html):
    """Extract upcoming picks, strictly stopping before historical results.

    The header and data rows are sometimes separate HTML tables, so traverse
    document-order rows instead of assuming they are all children of one table.
    """
    soup = BeautifulSoup(html, 'html.parser')
    rows = soup.find_all('tr')
    start = next((i for i, row in enumerate(rows) if _is_picks_header(row)), None)
    if start is None:
        # IMPORTANT: A missing table by itself means FAILED, not EMPTY.
        # SoccerRating explicitly says "Sorry, we have no new betting picks"
        # when there are no upcoming selections. Require both the authentic
        # Strategy Creator marker and the historical-results heading as well,
        # to avoid treating an error/login/loading page as an empty strategy.
        body = soup.body if soup.body else soup
        visible = _clean(body.get_text(' ', strip=True))
        if (NO_PICKS_RE.search(visible) and CREATOR_RE.search(visible)
                and HISTORY_RE.search(visible)):
            return []
        raise SourceUnavailable(
            'Neither a valid Betting Picks table nor SoccerRating’s explicit '
            'no-new-picks notice was found. Login may have expired, or '
            'SoccerRating changed its page layout.')

    matches = []
    failed = []
    seen_keys = set()
    for row in rows[start + 1:]:
        content = ' '.join(_text(c) for c in _cells(row))
        if HISTORY_RE.search(content):
            break
        item = _match_row(row)
        if item:
            key = (item['date'], item['home'].casefold(), item['away'].casefold())
            if key not in seen_keys:
                matches.append(item)
                seen_keys.add(key)
        elif _looks_like_match(row):
            # Fail visibly instead of claiming success with zero picks when
            # source columns have changed. Redact/truncate any page content.
            failed.append(_clean(content)[:160])

    if failed:
        raise SourceUnavailable(
            f'Found {len(failed)} Betting Picks candidate row(s) that could not '
            'be safely parsed. Import paused; first row: ' + failed[0])
    return matches


def login_window():
    try:
        from playwright.sync_api import sync_playwright
    except ImportError as exc:
        raise SourceUnavailable('Playwright not installed. Run INSTALL_SOCCERRATING_OPTIONAL_COMPONENTS.bat.') from exc

    with sync_playwright() as pw:
        try:
            context = pw.chromium.launch_persistent_context(
                str(PROFILE), channel='msedge', headless=False,
                viewport={'width': 1320, 'height': 800})
        except Exception as exc:
            raise SourceUnavailable('Microsoft Edge could not open: ' + str(exc)) from exc
        try:
            page = context.pages[0] if context.pages else context.new_page()
            page.goto(STRATEGY_URLS['2.00'], wait_until='domcontentloaded', timeout=30000)
            print('Sign into SoccerRating in this Edge window, verify your saved strategies, '
                  'then close the window.', flush=True)
            while context.pages:
                time.sleep(1)
        finally:
            context.close()


def collect_from_saved_session():
    """Independently scan all seven saved strategies.

    Returns {'matches': {strategy: picks}, 'statuses': {strategy: details}}.
    The caller can safely commit successful strategies even when another has a
    site/layout error. A page with a recognized picks header but no pick rows is
    marked EMPTY; an unrecognized page is never counted as an empty result.
    """
    try:
        from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
    except ImportError as exc:
        raise SourceUnavailable('Playwright missing. Run the optional installer.') from exc
    if not PROFILE.exists():
        raise SourceUnavailable('No saved browser session. Open Connect SoccerRating and sign in first.')

    result = {}
    statuses = {}
    with sync_playwright() as pw:
        try:
            context = pw.chromium.launch_persistent_context(
                str(PROFILE), channel='msedge', headless=True,
                viewport={'width': 1280, 'height': 900})
        except Exception as exc:
            raise SourceUnavailable('Saved browser profile is unavailable (close the login browser first): ' + str(exc)) from exc
        try:
            page = context.pages[0] if context.pages else context.new_page()
            # Go straight to each approved strategy. The /tips/ index is not
            # required, which avoids brittle sidebar matching and one request.
            for index, (strategy, target) in enumerate(STRATEGY_URLS.items()):
                if index:
                    time.sleep(1)  # Polite pacing; do not flood the source site.
                try:
                    # FA_COLLECTOR_TIMEOUT_RETRY_V1: one bounded navigation retry only.
                    # Never retry access denial, redirects, invalid page content, or parsing failures.
                    for attempt in range(2):
                        try:
                            response = page.goto(
                                target, wait_until='domcontentloaded',
                                timeout=25000 if attempt == 0 else 35000)
                            break
                        except PlaywrightTimeoutError:
                            if attempt:
                                raise SourceUnavailable(
                                    'Strategy navigation timed out twice (25s and 35s).')
                            print('SoccerRating strategy ' + strategy +
                                  ': navigation timed out; retrying once.', flush=True)
                            time.sleep(2)
                    status_code = response.status if response else None
                    if status_code is not None and status_code >= 400:
                        raise SourceUnavailable(
                            f'SoccerRating returned HTTP {status_code}; website access may be restricted.')
                    if not _valid_strategy_target(page.url, target):
                        raise SourceUnavailable(
                            'Strategy page redirected or does not match its approved URL.')
                    # Check page identity before accepting either a pick or an
                    # empty-state message as an authoritative result.
                    _verify_strategy_title(page.title(), strategy)
                    picks = _parse_after_ready(page)
                    result[strategy] = picks
                    statuses[strategy] = {'state': 'ok' if picks else 'empty',
                                          'found': len(picks), 'error': ''}
                    if picks:
                        print(f'SoccerRating strategy {strategy}: parsed {len(picks)} Betting Picks.', flush=True)
                    else:
                        print(f'SoccerRating strategy {strategy}: EMPTY — verified no upcoming Betting Picks.', flush=True)
                except SourceUnavailable as exc:
                    message = str(exc)[:240]
                    statuses[strategy] = {'state': 'error', 'found': 0, 'error': message}
                    print(f'SoccerRating strategy {strategy}: FAILED — {message}', flush=True)
                    if 'HTTP 429' in message or 'HTTP 403' in message:
                        # Do not try other strategies when the website denies access.
                        for remaining in STRATEGIES:
                            if remaining not in statuses:
                                statuses[remaining] = {'state': 'error', 'found': 0,
                                    'error': 'Scan paused after SoccerRating access restriction.'}
                        break
                except Exception as exc:
                    # Playwright sometimes raises before exposing the HTTP status.
                    # Unknown HTTP failures and connection resets pause this scan,
                    # rather than hammering an inaccessible website.
                    detail = str(exc)
                    stopped = any(token in detail for token in (
                        'ERR_HTTP_RESPONSE_CODE_FAILURE', 'ERR_CONNECTION_RESET',
                        'ERR_TOO_MANY_REQUESTS', 'ERR_BLOCKED_BY_CLIENT'))
                    message = ('Navigation rejected or connection closed; scan paused.' if stopped
                               else 'Browser navigation failed (' + type(exc).__name__ + ').')
                    statuses[strategy] = {'state': 'error', 'found': 0, 'error': message}
                    print(f'SoccerRating strategy {strategy}: FAILED — {message}', flush=True)
                    if stopped:
                        for remaining in STRATEGIES:
                            if remaining not in statuses:
                                statuses[remaining] = {'state': 'error', 'found': 0,
                                    'error': 'Scan paused after browser connection failure.'}
                        break
            # Network/navigation failures never masquerade as an empty strategy.
            for strategy in STRATEGIES:
                statuses.setdefault(strategy, {'state':'error','found':0,
                                               'error':'No verified strategy page was scanned.'})
            return {'matches': result, 'statuses': statuses}
        finally:
            context.close()


if __name__ == '__main__':
    if len(sys.argv) == 2 and sys.argv[1] == 'login':
        login_window()
    else:
        print('Run with: python soccerrating_connector.py login')
