# mk/report.py
import os
import sys
from pathlib import Path
from datetime import datetime, timezone

# Import common
sys.path.append(str(Path(__file__).parent))
from common import DIST_DIR

def generate_report():
    """
    Read build information from environment variables and generate Markdown report.
    Write to both GITHUB_STEP_SUMMARY and install/BUILD_REPORT.md
    """
    # Generate current UTC time directly in Python
    current_time = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")

    # Get information from environment variables (passed by Workflow)
    build_tag = os.environ.get("BUILD_TAG", "N/A")
    arch = os.environ.get("BUILD_ARCH", "unknown")
    os_name = os.environ.get("BUILD_OS", "unknown")
    is_release = os.environ.get("IS_RELEASE", "false") == "true"
    
    mfa_tag = os.environ.get("MFA_TAG", "Unknown")
    mfa_date = os.environ.get("MFA_DATE", "N/A")
    mfa_url = os.environ.get("MFA_URL", "")
    mfa_pre = os.environ.get("MFA_PRERELEASE", "false") == "true"

    # Format status text
    release_status = "[YES]" if is_release else "[NO]"
    mfa_type_status = "[PRE-RELEASE]" if mfa_pre else "[STABLE]"
    
    # Format links
    mfa_link = f"[{mfa_tag}]({mfa_url})" if mfa_url.startswith("http") else mfa_tag
    mfa_url_display = mfa_url if mfa_url.startswith("http") else "#"

    # Template content
    content = f"""
## Build Information
| Component | Details |
|-----------|---------|
| **Build Date** | {current_time} |
| **Build Tag** | `{build_tag}` |
| **Architecture** | `{arch}` |
| **OS** | `{os_name}` |
| **Is Release** | {release_status} |

## Dependencies (MFAAvalonia)
| Property | Value |
|----------|-------|
| **Version** | {mfa_link} |
| **Release Date** | {mfa_date} |
| **Type** | {mfa_type_status} |

## Links
- [MFAAvalonia Release]({mfa_url_display})

---
*Generated on {current_time}*
"""

    # 1. Write to GitHub Step Summary
    summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
    if summary_file:
        try:
            with open(summary_file, "a", encoding="utf-8") as f:
                f.write(f"# Build Report - {arch}\n")
                f.write(content)
            print("[OK] GITHUB_STEP_SUMMARY updated.")
        except Exception as e:
            print(f"[ERROR] Failed to write summary: {e}")

    # 2. Write to install/BUILD_REPORT.md
    if DIST_DIR.exists():
        report_path = DIST_DIR / "BUILD_REPORT.md"
        try:
            with open(report_path, "w", encoding="utf-8") as f:
                f.write("# Build Report\n")
                f.write(content)
                f.write("\n*Generated by GitHub Actions via mk/report.py*")
            print(f"[OK] Report file created at: {report_path}")
        except Exception as e:
            print(f"[ERROR] Failed to write report file: {e}")
    else:
        print(f"[WARN] Install directory {DIST_DIR} does not exist, skipping file report.")

if __name__ == "__main__":
    generate_report()