import psycopg2 as mdb
import psycopg2.extras
import smtplib
import json
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime

# Disable SSL warnings (matching PHP's CURLOPT_SSL_VERIFYPEER = 0)
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# --- DB connection ---
pg_config = {
    'host': '37.27.12.199',
    'user': 'axg_crm_new1',
    'password': 'Yyv1QT2JUMLyxt71cYLG',
    'dbname': 'axg_crm_new'
}

# Selenium API endpoint
SELENIUM_API_URL = 'http://135.181.199.23:5004/removee'

# Email configuration
EMAIL_USERNAME = 'AKIAYJJ2GCT4ZILVPU6C'
EMAIL_PASSWORD = 'BK/DjNVeavqxMZSBMBB/TGVbpHjiVXF7QZfF9E+NhTSh'
EMAIL_SENDER = 'removals@axghouse.com'
EMAIL_RECEIVERS = ['santhoshkasturi7@gmail.com', 'support@axghouse.com']

def check_link_status(url):
    """Check the status of a link using the Selenium API - matches PHP curl implementation"""
    try:
        # Match the exact PHP curl request format
        payload = json.dumps({'url': url})
        headers = {
            'Content-Type': 'application/json'
        }
        
        response = requests.post(
            SELENIUM_API_URL,
            data=payload,  # Use data instead of json to match curl POSTFIELDS
            headers=headers,
            timeout=120,
            allow_redirects=True,  # Equivalent to CURLOPT_FOLLOWLOCATION
            verify=False  # Equivalent to CURLOPT_SSL_VERIFYPEER = 0
        )
        
        # Return the response text directly (matching PHP's curl_exec return)
        return response.text.strip() if response.status_code == 200 else f"API_ERROR_{response.status_code}"
    except requests.exceptions.Timeout:
        return "ERROR: Request timeout"
    except requests.exceptions.RequestException as e:
        return f"ERROR: {str(e)}"
    except Exception as e:
        return f"ERROR: {str(e)}"

def get_expected_codes(good_link):
    """Get expected status codes based on link type"""
    if good_link == 1:
        return ['200']
    else:
        return ['404', '403']

def verify_link(link_data):
    """Verify a single link and return result"""
    url = link_data['link']
    # Handle NULL/None values - default to 0 (Bad Link)
    good_link = link_data.get('good_link')
    if good_link is None:
        good_link = 0
    
    expected_codes = get_expected_codes(good_link)
    actual_code = check_link_status(url)
    
    is_match = actual_code in expected_codes
    link_type = "Good Link" if good_link == 1 else "Bad Link"
    status = "✓ PASS" if is_match else "✗ FAIL"
    
    return {
        'id': link_data['id'],
        'url': url,
        'link_type': link_type,
        'expected_codes': expected_codes,
        'actual_code': actual_code,
        'status': status,
        'is_match': is_match
    }

# --- Connect to database ---
try:
    con = mdb.connect(**pg_config)
    con.autocommit = True
    cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
    
    # --- Query all test links ---
    query = """
    SELECT 
        id,
        link,
        good_link
    FROM test_links
    ORDER BY id ASC;
    """
    cur.execute(query)
    rows = cur.fetchall()
    
    if len(rows) == 0:
        print("No test links found in database.")
        con.close()
        exit(0)
    
    # --- Verify all links ---
    results = []
    for row in rows:
        result = verify_link(row)
        results.append(result)
        print(f"Checked: {result['url']} - {result['status']} (Expected: {result['expected_codes']}, Got: {result['actual_code']})")
    
    # --- Generate report statistics ---
    total_links = len(results)
    passed_links = sum(1 for r in results if r['is_match'])
    failed_links = total_links - passed_links
    good_links_count = sum(1 for r in results if r['link_type'] == 'Good Link')
    bad_links_count = total_links - good_links_count
    
    # --- Build HTML table with results ---
    table_rows = ""
    for result in results:
        status_color = "#28a745" if result['is_match'] else "#dc3545"
        table_rows += f"""
      <tr style="background-color: {'#d4edda' if result['is_match'] else '#f8d7da'};">
        <td>{result['id']}</td>
        <td><a href="{result['url']}" target="_blank" style="word-break: break-all; color: #007bff;">{result['url'][:80] + '...' if len(result['url']) > 80 else result['url']}</a></td>
        <td>{result['link_type']}</td>
        <td>{', '.join(result['expected_codes'])}</td>
        <td style="color: {status_color}; font-weight: bold;">{result['actual_code']}</td>
        <td style="color: {status_color}; font-weight: bold;">{result['status']}</td>
      </tr>
        """
    
    # --- Build HTML email ---
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    html = f"""
<html>
<head>
  <style>
    body {{
      font-family: Arial, sans-serif;
      background-color: #f9f9f9;
      color: #333;
      margin: 0;
      padding: 20px;
    }}
    .container {{
      background: #ffffff;
      max-width: 1200px;
      margin: auto;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }}
    h2 {{
      text-align: center;
      background: {'#dc3545' if failed_links > 0 else '#28a745'};
      color: white;
      padding: 12px;
      border-radius: 6px;
    }}
    .summary {{
      display: flex;
      justify-content: space-around;
      margin: 20px 0;
      flex-wrap: wrap;
    }}
    .summary-box {{
      background: #f8f9fa;
      border: 2px solid #dee2e6;
      border-radius: 8px;
      padding: 15px;
      text-align: center;
      min-width: 150px;
      margin: 10px;
    }}
    .summary-box h3 {{
      margin: 0 0 10px 0;
      color: #495057;
      font-size: 14px;
    }}
    .summary-box .number {{
      font-size: 32px;
      font-weight: bold;
      color: #007bff;
    }}
    .summary-box.success .number {{
      color: #28a745;
    }}
    .summary-box.danger .number {{
      color: #dc3545;
    }}
    table {{
      border-collapse: collapse;
      width: 100%;
      margin-top: 15px;
      font-size: 12px;
    }}
    th, td {{
      border: 1px solid #ddd;
      padding: 10px;
      text-align: left;
    }}
    th {{
      background-color: #f2f2f2;
      font-weight: bold;
      position: sticky;
      top: 0;
    }}
    tr:hover {{ background-color: #f1f1f1; }}
    .footer {{
      text-align: center;
      font-size: 12px;
      color: #666;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #dee2e6;
    }}
  </style>
</head>
<body>
  <div class="container">
    <h2>🔗 Daily Test Links Verification Report</h2>
    
    <div class="summary">
      <div class="summary-box">
        <h3>Total Links</h3>
        <div class="number">{total_links}</div>
      </div>
      <div class="summary-box success">
        <h3>Passed</h3>
        <div class="number">{passed_links}</div>
      </div>
      <div class="summary-box danger">
        <h3>Failed</h3>
        <div class="number">{failed_links}</div>
      </div>
      <div class="summary-box">
        <h3>Good Links</h3>
        <div class="number">{good_links_count}</div>
      </div>
      <div class="summary-box">
        <h3>Bad Links</h3>
        <div class="number">{bad_links_count}</div>
      </div>
    </div>
    
    <table>
      <tr>
        <th>ID</th>
        <th>Link URL</th>
        <th>Link Type</th>
        <th>Expected Codes</th>
        <th>Actual Code</th>
        <th>Status</th>
      </tr>
      {table_rows}
    </table>
    
    <div class="footer">
      <p><strong>Report Generated:</strong> {current_time}</p>
      <p>Axghouse Antipiracy &copy; {datetime.now().year} | Daily Link Verification Monitor</p>
    </div>
  </div>
</body>
</html>
    """
    
    # --- Send email ---
    msg = MIMEMultipart("alternative")
    msg["Subject"] = f"Daily Test Links Report: {passed_links}/{total_links} Passed ({failed_links} Failed)"
    msg["From"] = f"Axghouse Antipiracy <{EMAIL_SENDER}>"
    msg["To"] = ", ".join(EMAIL_RECEIVERS)
    msg.attach(MIMEText(html, "html"))
    
    try:
        server = smtplib.SMTP('email-smtp.eu-west-1.amazonaws.com', 587)
        server.starttls()
        server.login(EMAIL_USERNAME, EMAIL_PASSWORD)
        server.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
        server.quit()
        print(f"\n✅ Report email sent successfully!")
        print(f"   Total Links: {total_links} | Passed: {passed_links} | Failed: {failed_links}")
    except Exception as e:
        print(f"\n❌ Error sending email: {str(e)}")
    
    con.close()
    
except Exception as e:
    print(f"❌ Error: {str(e)}")
    exit(1)

