"""
Google Search Console integration via the Search Console API.

Setup required (see README):
1. Enable "Google Search Console API" on your GCP project.
2. In Search Console > Settings > Users and permissions, add the service
   account's email as a "Full" or "Restricted" user for each client's
   property (sc-domain:example.com or https://example.com/).
"""
from datetime import date, timedelta
from googleapiclient.discovery import build
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/webmasters.readonly']


def _get_service(credentials_source):
    """credentials_source may be a parsed service-account JSON dict (from the
    Settings page) or a file path string (from GOOGLE_SERVICE_ACCOUNT_FILE)."""
    if isinstance(credentials_source, dict):
        credentials = service_account.Credentials.from_service_account_info(
            credentials_source, scopes=SCOPES
        )
    else:
        credentials = service_account.Credentials.from_service_account_file(
            credentials_source, scopes=SCOPES
        )
    return build('searchconsole', 'v1', credentials=credentials)


def fetch_site_summary(service_account_file, gsc_site_url, target_date=None):
    """Site-level totals (clicks/impressions/ctr/position) for a single day."""
    if target_date is None:
        target_date = date.today() - timedelta(days=3)  # GSC data lags ~2-3 days

    service = _get_service(service_account_file)
    date_str = target_date.strftime('%Y-%m-%d')

    body = {
        'startDate': date_str,
        'endDate': date_str,
        'dimensions': [],
    }
    response = service.searchanalytics().query(
        siteUrl=gsc_site_url, body=body
    ).execute()

    rows = response.get('rows', [])
    if not rows:
        return {'clicks': 0, 'impressions': 0, 'ctr': 0, 'position': 0, 'date': target_date}

    row = rows[0]
    return {
        'clicks': row.get('clicks', 0),
        'impressions': row.get('impressions', 0),
        'ctr': round(row.get('ctr', 0) * 100, 2),
        'position': round(row.get('position', 0), 1),
        'date': target_date,
    }


def fetch_top_queries(service_account_file, gsc_site_url, days=7, limit=100):
    """Top search queries by clicks over trailing `days` window, with page dimension."""
    service = _get_service(service_account_file)
    end = date.today() - timedelta(days=3)
    start = end - timedelta(days=days - 1)

    body = {
        'startDate': start.strftime('%Y-%m-%d'),
        'endDate': end.strftime('%Y-%m-%d'),
        'dimensions': ['query', 'page'],
        'rowLimit': limit,
    }
    response = service.searchanalytics().query(
        siteUrl=gsc_site_url, body=body
    ).execute()

    results = []
    for row in response.get('rows', []):
        keys = row.get('keys', ['', ''])
        results.append({
            'query': keys[0],
            'page': keys[1] if len(keys) > 1 else '',
            'clicks': row.get('clicks', 0),
            'impressions': row.get('impressions', 0),
            'ctr': round(row.get('ctr', 0) * 100, 2),
            'position': round(row.get('position', 0), 1),
        })
    return results


def list_sites(credentials_source):
    """Every GSC property this service account can access."""
    service = _get_service(credentials_source)
    return service.sites().list().execute().get('siteEntry', [])


def _derive_display(site_url):
    """GSC siteUrl -> (clean https url, display name). The raw siteUrl itself
    must be stored verbatim as gsc_site_url — GSC requires exact matches
    (including the sc-domain: prefix or trailing slash) for later API calls."""
    if site_url.startswith('sc-domain:'):
        domain = site_url[len('sc-domain:'):]
        return f'https://{domain}', domain
    clean = site_url.rstrip('/')
    return clean, clean.split('//', 1)[-1]


def inspect_url(service_account_file, gsc_site_url, page_url):
    """
    Runs the URL Inspection API to determine indexing status and,
    critically, WHY a page might not be indexed.
    """
    service = _get_service(service_account_file)
    body = {
        'inspectionUrl': page_url,
        'siteUrl': gsc_site_url,
    }
    response = service.urlInspection().index().inspect(body=body).execute()
    result = response.get('inspectionResult', {})
    index_status = result.get('indexStatusResult', {})

    coverage_state = index_status.get('coverageState', 'Unknown')
    indexing_state = index_status.get('indexingState', 'Unknown')
    verdict = index_status.get('verdict', 'UNKNOWN')
    robots_txt_state = index_status.get('robotsTxtState', 'Unknown')
    last_crawl_time = index_status.get('lastCrawlTime')
    sitemap = index_status.get('sitemap', [None])
    sitemap = sitemap[0] if sitemap else None

    # Build a human-readable reason for "why not indexed"
    reason_parts = []
    if verdict != 'PASS':
        if indexing_state and indexing_state != 'INDEXING_ALLOWED':
            reason_parts.append(f"Indexing blocked: {indexing_state}")
        if robots_txt_state and robots_txt_state != 'ALLOWED':
            reason_parts.append(f"Blocked by robots.txt ({robots_txt_state})")
        if coverage_state:
            reason_parts.append(f"Coverage: {coverage_state}")
        if not last_crawl_time:
            reason_parts.append("Page has not been crawled by Google yet")
    reason = "; ".join(reason_parts) if reason_parts else "Indexed normally"

    return {
        'coverage_state': coverage_state,
        'indexing_state': indexing_state,
        'verdict': verdict,
        'robots_txt_state': robots_txt_state,
        'last_crawl_time': last_crawl_time,
        'sitemap': sitemap,
        'reason': reason,
    }
